Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify UI scaler #1157

Merged
merged 21 commits into from
Sep 8, 2021
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 20 additions & 7 deletions TLM/CSUtil.Commons/Log.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ namespace CSUtil.Commons {
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Linq;
using UnityEngine;
using Debug = UnityEngine.Debug;

Expand Down Expand Up @@ -40,9 +40,9 @@ namespace CSUtil.Commons {
public static class Log {
private static readonly object LogLock = new object();

// TODO refactor log filename to configuration
private static readonly string LogFilename
= Path.Combine(Application.dataPath, "TMPE.log");
private const string LOG_FILE_NAME = "TMPE.log";

private static readonly string LogFilePath;

private enum LogLevel {
Trace,
Expand All @@ -56,8 +56,21 @@ private enum LogLevel {

static Log() {
try {
if (File.Exists(LogFilename)) {
File.Delete(LogFilename);
string dir = Application.dataPath;
LogFilePath = Path.Combine(dir, LOG_FILE_NAME);
if (File.Exists(LogFilePath)) {
File.Delete(LogFilePath); // delete old file to avoid confusion.
}

var args = Environment.GetCommandLineArgs().ToList();
int index = args.IndexOf("-logFile");
if (index >= 0) {
dir = args[index + 1];
dir = Path.GetDirectoryName(dir); // drop output_log.txt
LogFilePath = Path.Combine(dir, LOG_FILE_NAME);
if (File.Exists(LogFilePath)) {
File.Delete(LogFilePath);
}
}
}
catch (Exception e) {
Expand Down Expand Up @@ -189,7 +202,7 @@ public static void NotImpl(string what) {

private static void LogToFile(string log, LogLevel level) {
lock(LogLock){
using (StreamWriter w = File.AppendText(LogFilename)) {
using (StreamWriter w = File.AppendText(LogFilePath)) {
long secs = _sw.ElapsedTicks / Stopwatch.Frequency;
long fraction = _sw.ElapsedTicks % Stopwatch.Frequency;
w.WriteLine(
Expand Down
6 changes: 3 additions & 3 deletions TLM/TLM/State/ConfigData/Main.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ public class Main {
public byte GuiOpacity = 75;

/// <summary>User interface scale for TM:PE. Unit: percents, range: 30..200f.</summary>
public float GuiScale = 100f;
public float GuiScalePercent = 100f;

/// <summary>
/// If checked, will use <see cref="ColossalFramework.UI.UIView"/> resolution instead of
/// what <see cref="UnityEngine.Screen"/> object returns.
/// if checked, size remains constnat but pixel count changes when resolution changes. Quality drops with lower resolutions.
/// if unchecked checked, size changes constnat but pixel count remains the same. Maintains same image quality for all resolution.
/// </summary>
public bool GuiScaleToResolution = true;

Expand Down
12 changes: 6 additions & 6 deletions TLM/TLM/State/OptionsTabs/OptionsGeneralTab.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ internal static void MakeSettings_General(ExtUITabstrip tabStrip) {
min: 50,
max: 200,
step: 5,
defaultValue: GlobalConfig.Instance.Main.GuiScale,
defaultValue: GlobalConfig.Instance.Main.GuiScalePercent,
eventCallback: OnGuiScaleChanged) as UISlider;
_guiScaleSlider.parent.Find<UILabel>("Label").width = 500;

Expand Down Expand Up @@ -259,13 +259,13 @@ private static void OnGuiScaleChanged(float newVal) {
_guiScaleSlider.tooltip
= string.Format(
T("General.Tooltip.Format:GUI scale: {0}%"),
GlobalConfig.Instance.Main.GuiScale);
GlobalConfig.Instance.Main.GuiScalePercent);
if (TMPELifecycle.Instance.IsGameLoaded) {
_guiScaleSlider.RefreshTooltip();
}

GlobalConfig.WriteConfig();
Log._Debug($"GuiScale changed to {GlobalConfig.Instance.Main.GuiScale}");
Log._Debug($"GuiScale changed to {GlobalConfig.Instance.Main.GuiScalePercent}");
}

/// <summary>User clicked [scale GUI to screen resolution] checkbox.</summary>
Expand All @@ -276,7 +276,7 @@ private static void OnGuiScaleToResChanged(float newVal) {
}

GlobalConfig.WriteConfig();
Log._Debug($"GuiScale changed to {GlobalConfig.Instance.Main.GuiScale}");
Log._Debug($"GuiScale changed to {GlobalConfig.Instance.Main.GuiScalePercent}");
}

private static void OnOverlayTransparencyChanged(float newVal) {
Expand Down Expand Up @@ -375,8 +375,8 @@ public static void SetGuiTransparency(byte val) {
}

public static void SetGuiScale(float val) {
bool changed = (int)val != (int)GlobalConfig.Instance.Main.GuiScale;
GlobalConfig.Instance.Main.GuiScale = val;
bool changed = (int)val != (int)GlobalConfig.Instance.Main.GuiScalePercent;
GlobalConfig.Instance.Main.GuiScalePercent = val;

if (changed && _guiScaleSlider != null) {
_guiScaleSlider.value = val;
Expand Down
52 changes: 15 additions & 37 deletions TLM/TLM/U/UIScaler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,55 +8,32 @@ namespace TrafficManager.U {
/// https://github.com/kianzarrin/Skylines-ModTools/blob/master/Debugger/UI/UIScaler.cs
/// </summary>
public static class UIScaler {
public static bool TryGetScreenResolution(out Vector2 resolution) {
UIView uIView = UIView.GetAView();
if (uIView) {
resolution = uIView.GetScreenResolution();
return true;
}

resolution = default;
return false;
}

private static float BaseResolutionX {
get {
if (TryGetScreenResolution(out Vector2 resolution)) {
// 1920f if aspect ratio is 16:9;
return resolution.x;
}
private static float BaseResolutionX => UIView.GetAView().GetScreenResolution().x;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd reduce GetAView() calls to a minimum.
Call it once and cache it.
The method searches every time for the first UIView even though the value never changes.
Also the method is implemented via LINQ and will cause heap allocations each time.


return 1080f * AspectRatio;
}
}

private static float BaseResolutionY {
get {
if (TryGetScreenResolution(out Vector2 resolution)) {
// always 1080f. But we keep this code for the sake of future proofing
return resolution.y;
}

return 1080f;
}
}
private static float BaseResolutionY => UIView.GetAView().GetScreenResolution().y;

public static float AspectRatio => Screen.width / (float)Screen.height;

/// <summary>Shortcut to reach global main config containing GuiScale.</summary>
private static State.ConfigData.Main Config => GlobalConfig.Instance.Main;

/// <summary>
/// Maximum projected width of GUI space when GUI.matrix = ScaleMatrix
/// </summary>
public static float MaxWidth {
get {
float ret = Config.GuiScaleToResolution ? BaseResolutionX : Screen.width;
return ret / Config.GuiScale;
return ret / UIScale;
}
}

/// <summary>
/// Maximum projected height of GUI space when GUI.matrix = ScaleMatrix
/// </summary>
public static float MaxHeight {
get {
float ret = Config.GuiScaleToResolution ? BaseResolutionY : Screen.height;
return ret / Config.GuiScale;
return ret / UIScale;
}
}

Expand All @@ -68,11 +45,13 @@ public static float UIAspectScale {
}
}

public static float UIScale => GlobalConfig.Instance.Main.GuiScale * 0.01f;

public static float UIScale => Config.GuiScalePercent * 0.01f;

public static Matrix4x4 ScaleMatrix => Matrix4x4.Scale(Vector3.one * UIScaler.UIScale);
public static Matrix4x4 ScaleMatrix => Matrix4x4.Scale(Vector3.one * UIAspectScale);

/// <summary>
/// Mouse position in GUI space when GUI.matrix = ScaleMatrix
/// </summary>
public static Vector2 MousePosition {
get {
var mouse = Input.mousePosition;
Expand All @@ -87,7 +66,6 @@ public static Vector2 MousePosition {
/// <param name="screenPos">Pixel position.</param>
/// <returns>GUI space position.</returns>
internal static Vector2 ScreenPointToGuiPoint(Vector2 screenPos) {
// TODO: Optimize, this is frequently called
return new(
x: screenPos.x * BaseResolutionX / Screen.width,
y: screenPos.y * BaseResolutionY / Screen.height);
Expand Down
4 changes: 2 additions & 2 deletions TLM/TLM/UI/LegacySubTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,8 +195,8 @@ public virtual string GetTutorialKey() {

protected void DragWindow(ref Rect window) {
Vector2 resolution = UIView.GetAView().GetScreenResolution();
window.x = Mathf.Clamp(window.x, 0, resolution.x - window.width);
window.y = Mathf.Clamp(window.y, 0, resolution.y - window.height);
window.x = Mathf.Clamp(window.x, 0, UIScaler.MaxWidth - window.width);
window.y = Mathf.Clamp(window.y, 0, UIScaler.MaxHeight - window.height);

bool primaryMouseDown = Input.GetMouseButton(0);
if (primaryMouseDown) {
Expand Down
6 changes: 4 additions & 2 deletions TLM/TLM/UI/SubTools/SpeedLimits/SpeedLimitsTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ namespace TrafficManager.UI.SubTools.SpeedLimits {
using UnityEngine;
using static TrafficManager.Util.Shortcuts;
using TrafficManager.Util.Extensions;
using TrafficManager.U;

public class SpeedLimitsTool : LegacySubTool {
public const int
Expand Down Expand Up @@ -142,6 +143,8 @@ public override void OnSecondaryClickOverlay() {

public override void OnToolGUI(Event e) {
base.OnToolGUI(e);
var oldMatrix = GUI.matrix;
GUI.matrix = UIScaler.ScaleMatrix;

string unitTitle = string.Format(
" ({0})",
Expand Down Expand Up @@ -176,8 +179,7 @@ public override void OnToolGUI(Event e) {
&& defaultsWindowRect.Contains(
Event.current.mousePosition));

// overlayHandleHovered = false;
// ShowSigns(false);
GUI.matrix = oldMatrix;
}

private static NetLane[] laneBuffer => NetManager.instance.m_lanes.m_buffer;
Expand Down
14 changes: 10 additions & 4 deletions TLM/TLM/UI/SubTools/TimedTrafficLights/TimedTrafficLightsTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ namespace TrafficManager.UI.SubTools.TimedTrafficLights {
using TrafficManager.API.TrafficLight;
using TrafficManager.Manager.Impl;
using TrafficManager.State;
using TrafficManager.U;
using TrafficManager.UI.MainMenu.OSD;
using TrafficManager.UI.Textures;
using TrafficManager.Util;
Expand Down Expand Up @@ -1098,13 +1099,16 @@ private string GetStepChangeMetricDescription(StepChangeMetric metric) {
private void GuiTimedTrafficLightsNode() {
_cursorInSecondaryPanel = false;

var oldMatrix = GUI.matrix;
GUI.matrix = UIScaler.ScaleMatrix;
_windowRect2 = GUILayout.Window(
id: 252,
screenRect: _windowRect2,
func: _guiTimedTrafficLightsNodeWindowDelegate,
text: T("TTL.Window.Title:Select nodes"),
style: WindowStyle,
options: EmptyOptionsArray);
GUI.matrix = oldMatrix;

_cursorInSecondaryPanel = _windowRect2.Contains(Event.current.mousePosition);
}
Expand All @@ -1115,6 +1119,8 @@ private void GuiTimedTrafficLightsNode() {
private void GuiTimedTrafficLights() {
_cursorInSecondaryPanel = false;

var oldMatrix = GUI.matrix;
GUI.matrix = UIScaler.ScaleMatrix;
_windowRect = GUILayout.Window(
id: 253,
screenRect: _windowRect,
Expand All @@ -1124,11 +1130,8 @@ private void GuiTimedTrafficLights() {
options: EmptyOptionsArray);

_cursorInSecondaryPanel = _windowRect.Contains(Event.current.mousePosition);
GUI.matrix = oldMatrix;

GUI.matrix = Matrix4x4.TRS(
new Vector3(0, 0, 0),
Quaternion.identity,
new Vector3(1, 1, 1)); // revert scaling
ShowGUI();
}

Expand All @@ -1138,6 +1141,8 @@ private void GuiTimedTrafficLights() {
private void GuiTimedTrafficLightsCopy() {
_cursorInSecondaryPanel = false;

var oldMatrix = GUI.matrix;
GUI.matrix = UIScaler.ScaleMatrix;
_windowRect2 = GUILayout.Window(
id: 255,
screenRect: _windowRect2,
Expand All @@ -1147,6 +1152,7 @@ private void GuiTimedTrafficLightsCopy() {
options: EmptyOptionsArray);

_cursorInSecondaryPanel = _windowRect2.Contains(Event.current.mousePosition);
GUI.matrix = oldMatrix;
}

private void GuiTimedTrafficLightsPasteWindow(int num) {
Expand Down