AlicizaX/Client/Assets/InputGlyph/InputGlyphDatabase.cs
2025-12-10 17:38:31 +08:00

100 lines
3.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;
namespace AlicizaX.InputGlyph
{
[Serializable]
public class GlyphEntry
{
public Sprite Sprite;
public InputAction action;
}
[Serializable]
public class DeviceGlyphTable
{
// 改为使用字符串名称来区分 table会序列化
public string deviceName;
public TMP_SpriteAsset tmpAsset;
public List<GlyphEntry> entries = new List<GlyphEntry>();
}
[CreateAssetMenu(fileName = "InputGlyphDatabase", menuName = "InputGlyphs/InputGlyphDatabase", order = 400)]
public class InputGlyphDatabase : ScriptableObject
{
public List<DeviceGlyphTable> tables = new List<DeviceGlyphTable>();
// 当 FindEntryByControlPath 传空 path 时返回的占位 sprite
public Sprite placeholderSprite;
// 按名字获取 tablename 精确匹配,不区分大小写)
public DeviceGlyphTable GetTable(string deviceName)
{
if (string.IsNullOrEmpty(deviceName)) return null;
if (tables == null) return null;
for (int i = 0; i < tables.Count; ++i)
{
var t = tables[i];
if (t == null) continue;
if (string.Equals(t.deviceName, deviceName, StringComparison.OrdinalIgnoreCase))
return t;
}
return null;
}
// 为兼容保留接受枚举并映射为常用名称Keyboard, Xbox, PlayStation
public DeviceGlyphTable GetTable(InputDeviceWatcher.InputDeviceCategory device)
{
string name = "Other";
switch (device)
{
case InputDeviceWatcher.InputDeviceCategory.Keyboard: name = "Keyboard"; break;
case InputDeviceWatcher.InputDeviceCategory.Xbox: name = "Xbox"; break;
case InputDeviceWatcher.InputDeviceCategory.PlayStation: name = "PlayStation"; break;
default: name = "Xbox"; break; // 与原逻辑相同Other -> Xbox
}
return GetTable(name);
}
public Sprite FindSprite(string controlPath, InputDeviceWatcher.InputDeviceCategory device)
{
var entry = FindEntryByControlPath(controlPath, device);
if (string.IsNullOrEmpty(controlPath) || entry == null)
{
return placeholderSprite;
}
return entry.Sprite;
}
public GlyphEntry FindEntryByControlPath(string controlPath, InputDeviceWatcher.InputDeviceCategory device)
{
var t = GetTable(device);
if (t != null)
{
for (int i = 0; i < t.entries.Count; ++i)
{
var e = t.entries[i];
if (e == null) continue;
if (e.action == null) continue;
if (e.action.bindings.Count <= 0) continue;
foreach (var binding in e.action.bindings)
{
if (string.Equals(controlPath, binding.path, StringComparison.OrdinalIgnoreCase))
{
return e;
}
}
}
}
return null;
}
}
}