Skip to content

Commit

Permalink
style: Various improvements.
Browse files Browse the repository at this point in the history
  • Loading branch information
freezy committed Jan 14, 2025
1 parent 451af25 commit 6abd49f
Show file tree
Hide file tree
Showing 18 changed files with 181 additions and 135 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -34,20 +34,22 @@ public override VisualElement CreateInspectorGUI()
var inspectorUi = inspectorXml.Instantiate();
root.Add(inspectorUi);
var coilNameDropdown = root.Q<DropdownField>("coil-name");
var coilNameProp = serializedObject.FindProperty("_coilName");
var coilNameProp = serializedObject.FindProperty(nameof(CoilSoundComponent._coilName));
var availableCoils = GetAvailableCoils();
ConfigureDropdown(coilNameDropdown, coilNameProp, availableCoils);
return root;
}

private Dictionary<string, string> GetAvailableCoils()
{
if (target != null &&
target is Component &&
(target as Component).TryGetComponent<ICoilDeviceComponent>(out var coilDevice))
return coilDevice.AvailableCoils.ToDictionary(i => i.Id,
i => string.IsNullOrWhiteSpace(i.Description) ? i.Id : i.Description);
return new();
var targetComponent = target as Component;
if (targetComponent != null && targetComponent.TryGetComponent<ICoilDeviceComponent>(out var coilDevice)) {
return coilDevice.AvailableCoils.ToDictionary(
i => i.Id,
i => string.IsNullOrWhiteSpace(i.Description) ? i.Id : i.Description
);
}
return new Dictionary<string, string>();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,42 +48,48 @@ protected void InvalidSoundAssetHelpBox(VisualElement container)
"The selected sound asset is invalid. Make sure it has at least one audio clip.",
HelpBoxMessageType.Warning);
container.Add(helpBox);
var soundAssetProp = serializedObject.FindProperty("_soundAsset");
var soundAssetProp = serializedObject.FindProperty(nameof(SoundComponent._soundAsset));
UpdateVisibility(soundAssetProp);
helpBox.TrackPropertyValue(soundAssetProp, UpdateVisibility);

void UpdateVisibility(SerializedProperty soundAssetProp)
void UpdateVisibility(SerializedProperty prop)
{
var soundAsset = soundAssetProp.objectReferenceValue as SoundAsset;
if (soundAsset == null || soundAsset.IsValid())
var soundAsset = prop.objectReferenceValue as SoundAsset;
if (soundAsset == null || soundAsset.IsValid()) {
helpBox.style.display = DisplayStyle.None;
else

} else {
helpBox.style.display = DisplayStyle.Flex;
}
}
}

protected void MissingComponentHelpBox(VisualElement container)
{
if (target != null &&
target is SoundComponent) {
if (target != null && target is SoundComponent) {
var soundComp = target as SoundComponent;
var requiredType = soundComp.GetRequiredType();
if (requiredType != null && !soundComp.TryGetComponent(requiredType, out var _))
container.Add(new HelpBox($"This component needs a component of type " +
$"{requiredType.Name} on the same game object to work.",
if (requiredType != null && !soundComp.TryGetComponent(requiredType, out _)) {
container.Add(new HelpBox($"This component needs a component of type {requiredType.Name} on the same game object to work.",
HelpBoxMessageType.Error));
}
}
}

private bool AllTargetsSupportLoopingSoundAssets()
{
foreach (var target in targets) {
if (target == null)
foreach (var t in targets) {
if (t == null) {
continue;
if (target is not SoundComponent)
}

if (t is not SoundComponent) {
continue;
if (!(target as SoundComponent).SupportsLoopingSoundAssets())
}

if (!(t as SoundComponent).SupportsLoopingSoundAssets()) {
return false;
}
}
return true;
}
Expand All @@ -101,38 +107,38 @@ protected void InfiniteLoopHelpBox(VisualElement container)

void UpdateVisbility(SerializedObject obj)
{
var soundAssetProp = obj.FindProperty("_soundAsset");
var soundAsset = soundAssetProp.objectReferenceValue as SoundAsset;
if (soundAsset && soundAsset.Loop && !AllTargetsSupportLoopingSoundAssets())
var prop = obj.FindProperty(nameof(SoundComponent._soundAsset));
var soundAsset = prop.objectReferenceValue as SoundAsset;
if (soundAsset && soundAsset.Loop && !AllTargetsSupportLoopingSoundAssets()) {
helpBox.style.display = DisplayStyle.Flex;
else
} else {
helpBox.style.display = DisplayStyle.None;
}
}
}

protected static void ConfigureDropdown(DropdownField dropdown,
SerializedProperty boundProp,
Dictionary<string, string> idsToDisplayNames)
protected static void ConfigureDropdown(DropdownField dropdown, SerializedProperty boundProp, Dictionary<string, string> idsToDisplayNames)
{
var displayNamesToIds = idsToDisplayNames.ToDictionary(i => i.Value, i => i.Key);
dropdown.choices = displayNamesToIds.Keys.ToList();
UpdateDropdown(boundProp);
dropdown.RegisterValueChangedCallback(e => UpdateProperty(dropdown));
dropdown.TrackPropertyValue(boundProp, UpdateDropdown);

void UpdateProperty(DropdownField dropdown)
void UpdateProperty(DropdownField dd)
{
var displayName = dropdown.value;
var displayName = dd.value;
boundProp.stringValue = displayNamesToIds.GetValueOrDefault(displayName);
boundProp.serializedObject.ApplyModifiedPropertiesWithoutUndo();
}

void UpdateDropdown(SerializedProperty property)
{
var id = property.stringValue;
if (idsToDisplayNames.TryGetValue(id, out var displayName))
if (idsToDisplayNames.TryGetValue(id, out var displayName)) {
dropdown.value = displayName;
else if (string.IsNullOrEmpty(id) && idsToDisplayNames.Count > 0) {

} else if (string.IsNullOrEmpty(id) && idsToDisplayNames.Count > 0) {
dropdown.value = idsToDisplayNames.First().Value;
property.stringValue = idsToDisplayNames.First().Key;
property.serializedObject.ApplyModifiedPropertiesWithoutUndo();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,20 +34,22 @@ public override VisualElement CreateInspectorGUI()
var inspectorUi = inspectorXml.Instantiate();
root.Add(inspectorUi);
var switchNameDropdown = root.Q<DropdownField>("switch-name");
var switchNameProp = serializedObject.FindProperty("_switchName");
var switchNameProp = serializedObject.FindProperty(nameof(SwitchSoundComponent._switchName));
var availableSwitches = GetAvailableSwitches();
ConfigureDropdown(switchNameDropdown, switchNameProp, availableSwitches);
return root;
}

private Dictionary<string, string> GetAvailableSwitches()
{
if (target != null &&
target is Component &&
(target as Component).TryGetComponent<ISwitchDeviceComponent>(out var switchDevice))
return switchDevice.AvailableSwitches.ToDictionary(i => i.Id,
i => string.IsNullOrWhiteSpace(i.Description) ? i.Id : i.Description);
return new();
var targetComponent = target as Component;
if (targetComponent != null && targetComponent.TryGetComponent<ISwitchDeviceComponent>(out var switchDevice)) {
return switchDevice.AvailableSwitches.ToDictionary(
i => i.Id,
i => string.IsNullOrWhiteSpace(i.Description) ? i.Id : i.Description
);
}
return new Dictionary<string, string>();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

using UnityEngine;
using VisualPinball.Engine.VPT.Flipper;

namespace VisualPinball.Unity.Editor
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

using UnityEngine;
using VisualPinball.Engine.VPT.Plunger;

namespace VisualPinball.Unity.Editor
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

using UnityEngine;
using VisualPinball.Engine.VPT.Trough;

namespace VisualPinball.Unity.Editor
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ namespace VisualPinball.Unity
/// provides the virtual method OnEnableAfterAwake, which always runs after all
/// instances have run their Awake methods.
/// </summary>
public abstract class EnableAfterAwakeMonoBehaviour : MonoBehaviour
public abstract class EnableAfterAwakeComponent : MonoBehaviour
{
private bool _wasStartCalled;

Expand All @@ -36,13 +36,13 @@ private void Start()

private void OnEnable()
{
if (_wasStartCalled)
if (_wasStartCalled) {
OnEnableAfterAfterAwake();
}
}

protected virtual void OnEnableAfterAfterAwake()
{

}
}
}
1 change: 0 additions & 1 deletion VisualPinball.Unity/VisualPinball.Unity/Game/Player.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
using VisualPinball.Engine.Common;
using VisualPinball.Engine.Game;
using VisualPinball.Engine.Game.Engines;
using VisualPinball.Engine.VPT.Trigger;
using Color = VisualPinball.Engine.Math.Color;
using Logger = NLog.Logger;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

// ReSharper disable InconsistentNaming
using UnityEngine;

namespace VisualPinball.Unity
Expand All @@ -22,29 +23,33 @@ namespace VisualPinball.Unity
/// Start and or stop a sound when an event occurs that represents a binary state change,
/// such as a switch closing or a coil being energized.
/// </summary>
public abstract class BinaryEventSoundComponent<EventSourceType, EventArgsType>
: EventSoundComponent<EventSourceType, EventArgsType>
where EventSourceType : class
public abstract class BinaryEventSoundComponent<TEventSource, TEventArgs>
: EventSoundComponent<TEventSource, TEventArgs>
where TEventSource : class
{
public enum StartWhen { TurnedOn, TurnedOff };
public enum StopWhen { Never, TurnedOn, TurnedOff };

[SerializeField] private StartWhen _startWhen = StartWhen.TurnedOn;
[SerializeField] private StopWhen _stopWhen = StopWhen.Never;

protected override async void OnEvent(object sender, EventArgsType e)
protected override async void OnEvent(object sender, TEventArgs e)
{
bool enabled = InterpretAsBinary(e);
if ((enabled && _stopWhen == StopWhen.TurnedOn) ||
(!enabled && _stopWhen == StopWhen.TurnedOff))
bool isEnabled = InterpretAsBinary(e);
if ((isEnabled && _stopWhen == StopWhen.TurnedOn) ||
(!isEnabled && _stopWhen == StopWhen.TurnedOff))
{
Stop(allowFade: true);
}

if ((enabled && _startWhen == StartWhen.TurnedOn) ||
(!enabled && _startWhen == StartWhen.TurnedOff))
if ((isEnabled && _startWhen == StartWhen.TurnedOn) ||
(!isEnabled && _startWhen == StartWhen.TurnedOff))
{
await Play();
}
}

protected abstract bool InterpretAsBinary(EventArgsType e);
protected abstract bool InterpretAsBinary(TEventArgs e);

public override bool SupportsLoopingSoundAssets()
=> _stopWhen != StopWhen.Never;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

// ReSharper disable InconsistentNaming

using UnityEngine;
using System;

Expand All @@ -25,31 +27,32 @@ namespace VisualPinball.Unity
[AddComponentMenu("Visual Pinball/Sound/Coil Sound")]
public class CoilSoundComponent : BinaryEventSoundComponent<IApiCoil, NoIdCoilEventArgs>
{
[SerializeField, HideInInspector] private string _coilName;
[SerializeField, HideInInspector]
public string _coilName;

public override Type GetRequiredType() => typeof(ICoilDeviceComponent);

protected override bool TryFindEventSource(out IApiCoil coil)
{
coil = null;
var player = GetComponentInParent<Player>();
if (player == null)
if (player == null) {
return false;
}

foreach (var component in GetComponents<ICoilDeviceComponent>()) {
coil = player.Coil(component, _coilName);
if (coil != null)
if (coil != null) {
return true;
}
}
return false;
}

protected override void Subscribe(IApiCoil coil)
=> coil.CoilStatusChanged += OnEvent;
protected override void Subscribe(IApiCoil coil) => coil.CoilStatusChanged += OnEvent;

protected override void Unsubscribe(IApiCoil coil)
=> coil.CoilStatusChanged -= OnEvent;
protected override void Unsubscribe(IApiCoil coil) => coil.CoilStatusChanged -= OnEvent;

protected override bool InterpretAsBinary(NoIdCoilEventArgs e)
=> e.IsEnergized;
protected override bool InterpretAsBinary(NoIdCoilEventArgs e) => e.IsEnergized;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,26 @@
namespace VisualPinball.Unity
{
/// <summary>
/// Start and or stop a soud when an event occurs.
/// Start and or stop a sound when an event occurs.
/// </summary>
public abstract class EventSoundComponent<EventSourceType, EventArgsType> : SoundComponent where EventSourceType : class
public abstract class EventSoundComponent<TEventSource, TEventArgs> : SoundComponent where TEventSource : class
{
private EventSourceType _eventSource;
private TEventSource _eventSource;

protected abstract bool TryFindEventSource(out EventSourceType eventSource);
protected abstract void OnEvent(object sender, EventArgsType e);
protected abstract void Subscribe(EventSourceType eventSource);
protected abstract void Unsubscribe(EventSourceType eventSource);
protected abstract bool TryFindEventSource(out TEventSource eventSource);
protected abstract void OnEvent(object sender, TEventArgs e);
protected abstract void Subscribe(TEventSource eventSource);
protected abstract void Unsubscribe(TEventSource eventSource);

protected override void OnEnableAfterAfterAwake()
{
base.OnEnableAfterAfterAwake();
if (TryFindEventSource(out _eventSource))
if (TryFindEventSource(out _eventSource)) {
Subscribe(_eventSource);
else
Logger.Warn($"Could not find sound event source of type {typeof(EventSourceType).Name}." +
$" Make sure an appropriate component is attached");
} else {
Logger.Warn($"Could not find sound event source of type {typeof(TEventSource).Name}. " +
$"Make sure an appropriate component is attached");
}
}

protected override void OnDisable()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,15 @@ protected override bool TryFindEventSource(out IApiHittable hittable)
{
hittable = null;
var player = GetComponentInParent<Player>();
if (player == null)
if (player == null) {
return false;
}

foreach (var component in GetComponents<ItemComponent>()) {
hittable = player.TableApi.Hittable(component);
if (hittable != null)
if (hittable != null) {
return true;
}
}
return false;
}
Expand Down
Loading

0 comments on commit 6abd49f

Please sign in to comment.