using Foundations; using System; using System.Collections.Generic; using System.Globalization; using Amphora; using Annulus; using Azimuth; using Blacklight.Core; using Blacklight.Core.Cameras; using Blacklight.Core.Keyboard; using Clave; using Glass; using Glass.Blacklight; using Prism; namespace Konis.Testbed { /// /// The testbed's Glass UI: a control panel down the left, a status bar along the bottom, and the keys that mirror /// both. /// public class TestbedUi { private const double Margin = 8; private const double MinimumContentWidth = 150; private const double SectionGap = 12; private const double RowGap = 2; private const string RemoveSelectedText = "Remove selected"; private const string ClearText = "Clear"; private const string TuningText = "Tuning"; private readonly ParticleDemo demo; private readonly FrameStats stats; private readonly ExceptionSandbox sandbox = new ExceptionSandbox(typeof(Screen).Assembly); private readonly BlacklightGlassWorld world; private readonly IHostClipboard clipboard; private readonly TestbedSkin skin; private readonly CommandKeys commandKeys; private readonly Command[] effectCommands = new Command[Effects.All.Length]; private readonly Command pause; private readonly Command slower; private readonly Command faster; private readonly Command togglePreWarm; private readonly Command toggleLoop; private readonly Command cycleBackdrop; private readonly Command toggleFloor; private readonly Command toggleWall; private readonly Command togglePlanes; private readonly Command nextEmitter; private readonly Command previousEmitter; private readonly Command removeEmitter; private readonly Command clear; private readonly Command toggleTuning; private readonly Command respawn; private readonly List headings = new List(); private readonly RadioButton[] effectRadios; private readonly RadioButton[] speedRadios; private readonly RadioButton[] backdropRadios; private readonly Checkbox preWarmBox; private readonly Checkbox loopBox; private readonly Checkbox floorBox; private readonly Checkbox wallBox; private readonly Checkbox planesBox; private readonly StatusReadout readout; private readonly Panel statusBar; private readonly Panel speedBar; private readonly StatsPanel statsPanel; private readonly TuningPanel tuningPanel; private readonly GradientWindow gradientWindow; private readonly FunctionWindow functionWindow; private readonly SlabWindow slabWindow; private readonly Panel controlsPanel; private readonly Vector controlsSize; private readonly Vector speedSize; private readonly Vector statsSize; private readonly Scalar statusHeight; private int shownWindow = -1; /// /// Builds the UI over the window. Whatever is already on the input router stays behind the UI, so the UI gets /// first refusal on every click and key. The host owns the clipboard and disposes it. /// public TestbedUi(WindowHandle window, InputRouter inputRouter, IPointerLock pointerLock, ITextSource textSource, IHostClipboard clipboard, ParticleDemo demo, FrameStats stats) { this.demo = demo; this.stats = stats; this.clipboard = clipboard; world = new BlacklightGlassWorld(sandbox); commandKeys = new CommandKeys(world.screen.KeyboardManager); inputRouter.AddHighestPriority(commandKeys); world.BindToViewport(window, inputRouter); world.PointerLock = pointerLock; world.TextSource = textSource; world.Clipboard = clipboard; world.Scale = 1; // The fonts load when the renderer binds, so nothing that needs one can be built any earlier. skin = new TestbedSkin(world.renderer); world.screen.KeyboardManager.FocusMaterial = new DashedFrameMaterial( new SolidColorMaterial { Color = Color.FromArgb(255, 70, 150, 255) }) { DashLength = 3, MinGap = 2, Thickness = 1, Inset = 2, }; pause = commandKeys.Add(new Command("Pause", demo.TogglePause, Chord.OnPress(KeyCode.Space))); slower = commandKeys.Add( new Command("Slower", () => demo.StepSpeed(-1), Chord.OnPressOrRepeat(KeyCode.Minus))); faster = commandKeys.Add( new Command("Faster", () => demo.StepSpeed(1), Chord.OnPressOrRepeat(KeyCode.Equal))); togglePreWarm = commandKeys.Add( new Command("Pre-warm", () => demo.PreWarm = !demo.PreWarm, Chord.OnPress(KeyCode.P))); toggleLoop = commandKeys.Add( new Command("Loop", () => demo.Loop = !demo.Loop, Chord.OnPress(KeyCode.L))); cycleBackdrop = commandKeys.Add( new Command("Next background", demo.CycleBackdrop, Chord.OnPress(KeyCode.B))); toggleFloor = commandKeys.Add( new Command("Floor", () => demo.Floor = !demo.Floor, Chord.OnPress(KeyCode.F))); toggleWall = commandKeys.Add( new Command("Wall", () => demo.Wall = !demo.Wall, Chord.OnPress(KeyCode.V))); togglePlanes = commandKeys.Add( new Command("Show planes", () => demo.ShowPlanes = !demo.ShowPlanes, Chord.OnPress(KeyCode.G))); nextEmitter = commandKeys.Add(new Command("Next emitter", () => demo.SelectNeighbour(1), Chord.OnPressOrRepeat(KeyCode.BracketRight))); previousEmitter = commandKeys.Add(new Command("Previous emitter", () => demo.SelectNeighbour(-1), Chord.OnPressOrRepeat(KeyCode.BracketLeft))); removeEmitter = commandKeys.Add( new Command("Remove emitter", demo.RemoveSelected, Chord.OnPress(KeyCode.Delete))); clear = commandKeys.Add(new Command("Clear", demo.Clear, Chord.OnPress(KeyCode.Backspace))); toggleTuning = commandKeys.Add(new Command("Tuning panel", () => tuningPanel.Frame.Visible = !tuningPanel.Frame.Visible, Chord.OnPress(KeyCode.T))); respawn = commandKeys.Add(new Command("Respawn", demo.RespawnSelected, Chord.OnPress(KeyCode.R))); for (int i = 0; i < effectCommands.Length; i++) { int index = i; effectCommands[i] = commandKeys.Add(new Command( Effects.All[i].Name, () => demo.EffectIndex = index, Chord.OnPress(EffectKey(index)))); } // The buttons run the width of the panel, so it is as wide as the widest of them needs. Scalar contentWidth = Scalar.Max( MinimumContentWidth, Scalar.Max( skin.ButtonSizeFor(RemoveSelectedText).X, Scalar.Max(skin.ButtonSizeFor(ClearText).X, skin.ButtonSizeFor(TuningText).X))); Scalar rowHeight = skin.Text.SingleLineHeight + 6; var content = new RectAggregator( Rect.FromPositionAndSize(Vector.Zero, new Vector(contentWidth, 0)), new Vector(0, RowGap)); AddHeading(content.NewRow(rowHeight), "Effect"); string[] effectNames = new string[Effects.All.Length]; for (int i = 0; i < effectNames.Length; i++) { effectNames[i] = Effects.All[i].Name; } Panel effectColumn = BuildRadioColumn(effectNames, rowHeight, ref content, ShortcutTooltipFor, choose: index => demo.EffectIndex = index, out effectRadios); AddHeading(content.NewRow(rowHeight, margin: SectionGap), "Background"); string[] backdropNames = new string[Backdrop.All.Length]; for (int i = 0; i < backdropNames.Length; i++) { backdropNames[i] = Backdrop.All[i].Name; } Panel backdropColumn = BuildRadioColumn(backdropNames, rowHeight, ref content, BackdropTooltipFor, choose: index => demo.BackdropIndex = index, out backdropRadios); Label windHeading = AddHeading(content.NewRow(rowHeight, margin: SectionGap), WindText(0)); Slider windSlider = BuildWindSlider(content.NewRow(rowHeight), windHeading); preWarmBox = BuildCheckbox(content.NewRow(rowHeight, margin: SectionGap), "Pre-warm", "Start each spawn already running", togglePreWarm, isChecked => demo.PreWarm = isChecked); loopBox = BuildCheckbox(content.NewRow(rowHeight), "Loop", "Start an effect again where it was spawned once it finishes", toggleLoop, isChecked => demo.Loop = isChecked); floorBox = BuildCheckbox(content.NewRow(rowHeight, margin: SectionGap), "Floor", "Clip every particle below the ground", toggleFloor, isChecked => demo.Floor = isChecked); wallBox = BuildCheckbox(content.NewRow(rowHeight), "Wall", "Clip every particle past a wall to the right of the origin", toggleWall, isChecked => demo.Wall = isChecked); planesBox = BuildCheckbox(content.NewRow(rowHeight), "Show planes", "Draw a quad where the floor and the wall are", togglePlanes, isChecked => demo.ShowPlanes = isChecked); Scalar buttonHeight = skin.Button.BoundsSizeFor(new Vector(0, skin.Text.SingleLineHeight)).Y; Button removeButton = BuildButton(content.NewRow(buttonHeight, margin: SectionGap), RemoveSelectedText, ShortcutTooltip("Stop the selected emitter. Right-click an emitter to select it", removeEmitter, nextEmitter, previousEmitter), removeEmitter); Button clearButton = BuildButton(content.NewRow(buttonHeight), ClearText, ShortcutTooltip("Remove every effect from the world", clear), clear); Button tuningButton = BuildButton(content.NewRow(buttonHeight, margin: SectionGap), TuningText, ShortcutTooltip("Show or hide the panel that edits the effect's values", toggleTuning), toggleTuning); controlsPanel = new Panel { Material = skin.Panel, DebugName = "controls" }; controlsPanel.CanvasChildren.Add(effectColumn); controlsPanel.CanvasChildren.Add(backdropColumn); controlsPanel.CanvasChildren.Add(windSlider); controlsPanel.CanvasChildren.Add(preWarmBox); controlsPanel.CanvasChildren.Add(loopBox); controlsPanel.CanvasChildren.Add(floorBox); controlsPanel.CanvasChildren.Add(wallBox); controlsPanel.CanvasChildren.Add(planesBox); controlsPanel.CanvasChildren.Add(removeButton); controlsPanel.CanvasChildren.Add(clearButton); controlsPanel.CanvasChildren.Add(tuningButton); foreach (Control heading in headings) { controlsPanel.CanvasChildren.Add(heading); } controlsPanel.Bounds = Rect.FromPositionAndSize(Vector.Zero, skin.Panel.BoundsSizeFor(content.Rect.Size)); world.Controls.Add(controlsPanel); speedBar = BuildSpeedBar(buttonHeight, out speedRadios); world.Controls.Add(speedBar); readout =new StatusReadout(skin, stats.VerticalSync); statusBar = readout.Bar; world.Controls.Add(statusBar); statsPanel = new StatsPanel(skin); world.Controls.Add(statsPanel.Bar); gradientWindow = new GradientWindow(skin, window); functionWindow = new FunctionWindow(skin, window); slabWindow = new SlabWindow(skin); tuningPanel = new TuningPanel(skin, ShortcutTooltip("Start the selected effect again, so it takes values that only a new emitter shows", respawn), respawn.Run, text => clipboard.SetText(new StringChunks(text)), window, gradientWindow, functionWindow, slabWindow, new SpritePreviews(window, world.renderer, demo.Sprites)); world.Controls.Add(tuningPanel.Frame); // Added last so they float over the panels. world.Controls.Add(gradientWindow.Frame); world.Controls.Add(functionWindow.Frame); world.Controls.Add(slabWindow.Frame); // A panel is laid out for one size, and the screen squeezes the rect it is given and never the size it has. controlsSize = controlsPanel.Bounds.Size; speedSize = speedBar.Bounds.Size; statsSize = statsPanel.Bar.Bounds.Size; statusHeight = statusBar.Bounds.Height; // The windows open in the places the layout gives them, and are the user's to move after that. ScreenLayout layout = ArrangeScreen(); foreach (Window editor in new[] { gradientWindow.Frame, functionWindow.Frame, slabWindow.Frame }) { editor.Bounds = layout.EditorSlot(editor.Bounds.Size); } tuningPanel.Frame.Bounds = layout.Tuning; world.screen.OnSizeChanged += size => ArrangeScreen(); } // The digit row reads 1 to 9 and then 0, so the tenth effect takes the 0. private static KeyCode EffectKey(int index) { if (index > 9) { throw new ArgumentOutOfRangeException(nameof(index), index, "The digit row holds ten effects."); } return index == 9 ? KeyCode.Digit0 : (KeyCode)((int)KeyCode.Digit1 + index); } private Tooltip ShortcutTooltip(string text, params Command[] commands) { string line = text; foreach (Command command in commands) { string shortcut = command.ShortcutText(); if (shortcut != null) { line += $" ({command.Name}: {shortcut})"; } } return skin.TooltipFor(line); } private Tooltip ShortcutTooltipFor(int index) { return ShortcutTooltip($"Spawn {Effects.All[index].Name}", effectCommands[index]); } private Tooltip SpeedTooltipFor(int index) { if (index == 0) { return ShortcutTooltip("Pause the simulation", pause); } return ShortcutTooltip($"Run at {ParticleDemo.SpeedText(index)}", slower, faster); } private Tooltip BackdropTooltipFor(int index) { return ShortcutTooltip($"Draw over {Backdrop.All[index].Name}", cycleBackdrop); } private Label AddHeading(Rect slot, string text) { var heading = new Label(skin.HeadingText, text, Constraints.Tight(slot.Size)); heading.Bounds = slot; headings.Add(heading); return heading; } private static string WindText(decimal wind) { return "Wind " + wind.ToString("0", System.Globalization.CultureInfo.InvariantCulture); } private Slider BuildWindSlider(Rect slot, Label heading) { var slider = new Slider { SliderMaterial = skin.Slider, Grid = new NumberGrid { Min = -150, Max = 150, Resolution = 1, Step = 5, FineStep = 1, CoarseStep = 25, }, Bounds = slot, DebugName = "Wind slider", Tooltip = skin.TooltipFor("Blow every particle that takes wind sideways, in world units a second"), }; slider.OnValueChanged += value => { demo.World.Wind = new Vector3((double)value, 0, 0); heading.Text = WindText(value); }; return slider; } private Label LabelFor(Control control, string text) { var label = new Label(skin.Text, text, Constraints.Tight(control.CanvasRect.Size)); control.CanvasChildren.Add(label); return label; } // The column takes its place in the stack, and the rows are carved from a rect of the column's own. private Panel BuildRadioColumn(string[] names, Scalar rowHeight, ref RectAggregator content, Func tooltipFor, Action choose, out RadioButton[] radios) { Rect slot = content.NewRows(rowHeight, names.Length).Bounds; var column = new Panel { Material = Glass.Material.Invisible, AbsorbsMouse = false, Bounds = slot }; Rect inside = Rect.FromPositionAndSize(Vector.Zero, slot.Size); RectDivider rows = inside.NewRows(names.Length, RowGap); radios = new RadioButton[names.Length]; for (int i = 0; i < names.Length; i++) { var radio = new RadioButton(ButtonBehavior.Default) { UncheckedMaterial = skin.RadioOff, CheckedMaterial = skin.RadioOn, Bounds = rows[i], DebugName = $"{names[i]} radio", Tooltip = tooltipFor(i), }; LabelFor(radio, names[i]); column.CanvasChildren.Add(radio); radios[i] = radio; } RadioGroup.FromChildrenOf(column); // Selecting a radio by click tells the demo. Pressing a key changes the demo, and Sync checks the radio. for (int i = 0; i < radios.Length; i++) { int index = i; radios[i].OnCheckedChanged += isChecked => { if (isChecked) { choose(index); } }; } return column; } // A row of buttons, the one for the running speed lit. A radio group keeps exactly one lit. private Panel BuildSpeedBar(Scalar buttonHeight, out RadioButton[] radios) { var bar = new Panel { Material = skin.Panel, DebugName = "speed" }; var row = new RectAggregator( Rect.FromPositionAndSize(Vector.Zero, new Vector(0, buttonHeight)), new Vector(RowGap * 2, 0)); Scalar speedButtonWidth = 0; for (int i = 0; i < ParticleDemo.Speeds.Length; i++) { speedButtonWidth = Scalar.Max(speedButtonWidth, skin.ButtonSizeFor(ParticleDemo.SpeedText(i)).X); } RectDivider slots = row.NewCols(speedButtonWidth, ParticleDemo.Speeds.Length); radios = new RadioButton[ParticleDemo.Speeds.Length]; for (int i = 0; i < radios.Length; i++) { int index = i; string text = ParticleDemo.SpeedText(i); var radio = new RadioButton(ButtonBehavior.Default) { UncheckedMaterial = skin.Button, CheckedMaterial = skin.ButtonOn, Bounds = slots[i], DebugName = $"{text} speed", Tooltip = SpeedTooltipFor(i), }; radio.CanvasChildren.Add(new Label(skin.ButtonText, text, Constraints.Tight(radio.CanvasRect.Size))); radio.OnCheckedChanged += isChecked => { if (isChecked) { demo.SpeedIndex = index; } }; bar.CanvasChildren.Add(radio); radios[i] = radio; } RadioGroup.FromChildrenOf(bar); bar.Bounds = Rect.FromPositionAndSize(Vector.Zero, skin.Panel.BoundsSizeFor(row.Rect.Size)); return bar; } private Checkbox BuildCheckbox(Rect slot, string text, string tooltipText, Command command, Action set) { var box = new Checkbox(ButtonBehavior.Default) { UncheckedMaterial = skin.CheckOff, CheckedMaterial = skin.CheckOn, Bounds = slot, DebugName = $"{text} checkbox", Tooltip = ShortcutTooltip(tooltipText, command), }; LabelFor(box, text); box.OnCheckedChanged += isChecked => set(isChecked); return box; } private Button BuildButton(Rect slot, string text, Tooltip tooltip, Command command) { 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 ___) => command.Run(); return button; } // Puts every panel where the layout says and hands the layout back for the windows that float over them. The // windows aren't moved, since they are the user's to place once open. private ScreenLayout ArrangeScreen() { ScreenLayout returnMe = ScreenLayout.Arrange( world.screen.Size, controls: controlsSize, speed: speedSize, stats: statsSize, statusHeight: statusHeight, tuning: tuningPanel.Frame.Bounds.Size, margin: Margin); controlsPanel.Bounds = returnMe.Controls; speedBar.Bounds = returnMe.Speed; statsPanel.Bar.Bounds = returnMe.Stats; statusBar.Bounds = returnMe.Status; return returnMe; } // The demo's state is the truth, since keys change it without touching a control. private void SyncControls() { if (!effectRadios[demo.EffectIndex].Checked) { effectRadios[demo.EffectIndex].Checked = true; } if (!speedRadios[demo.SpeedIndex].Checked) { speedRadios[demo.SpeedIndex].Checked = true; } if (!backdropRadios[demo.BackdropIndex].Checked) { backdropRadios[demo.BackdropIndex].Checked = true; } if (preWarmBox.Checked != demo.PreWarm) { preWarmBox.Checked = demo.PreWarm; } if (loopBox.Checked != demo.Loop) { loopBox.Checked = demo.Loop; } if (floorBox.Checked != demo.Floor) { floorBox.Checked = demo.Floor; } if (wallBox.Checked != demo.Wall) { wallBox.Checked = demo.Wall; } if (planesBox.Checked != demo.ShowPlanes) { planesBox.Checked = demo.ShowPlanes; } } /// /// Advances the UI by one frame, with the pointer where the host last saw it. /// public void Update(Duration elapsed, PointerInput? pointer) { // First, so everything that throws during this frame is stamped with it. sandbox.Advance(elapsed); SyncControls(); // The panel edits the selected effect, or the one the next click would spawn. Effect tuned = Effects.All[demo.Selected != null ? demo.Selected.EffectIndex : demo.EffectIndex]; if (!ReferenceEquals(tuningPanel.Def, tuned.Def)) { tuningPanel.Bind(tuned.Def, tuned.Name); } if (stats.Windows != shownWindow) { shownWindow = stats.Windows; readout.Refresh(demo, stats); statsPanel.Refresh(demo.MeasureStats()); } world.Update(elapsed, pointer); } /// /// Queues the UI over whatever the window already holds. /// public void Render(WindowHandle window) { world.Render(window); } /// /// Lets go of the window. /// public void Unbind() { world.Unbind(); } } }