This commit is contained in:
Sahik committed 2026-10-27 16:51:24 +08:00
1 parent 9f928d391a
commit 48290de35e
13 files changed
+158 -58

No files matched your search

@@ -1,7 +0,0 @@
fileFormatVersion: 2
guid: aeeadfd0421657043b047d23f2112940
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,7 +0,0 @@
fileFormatVersion: 2
guid: 19f3b9a0980eb604497d2db8c8e4ea0e
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,7 +0,0 @@
fileFormatVersion: 2
guid: 794ee5cb61c74864fa0ba7639fed2e73
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,7 +0,0 @@
fileFormatVersion: 2
guid: 718863dcff53b784aa0ffc114381cdd7
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,7 +0,0 @@
fileFormatVersion: 2
guid: 518d1c1a2372e38479ca8a25bc9b0ee8
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,7 +0,0 @@
fileFormatVersion: 2
guid: 0aab1b18335e60849a9f0e022e548980
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+2 -2
View File
@@ -323,8 +323,8 @@ MonoBehaviour:
m_EditorClassIdentifier: Assembly-CSharp::AimAssist
perceptor: {fileID: 3127315678899527277}
playerLook: {fileID: 879551139689297706}
minFov: 5
maxFov: 30
minFov: 15
maxFov: 15
trackSpeed: {x: 2, y: 30}
--- !u!114 &132788102679742450
MonoBehaviour:
@@ -1,7 +0,0 @@
fileFormatVersion: 2
guid: 58f7e79a87c79824597746e8c1bfe400
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,7 +0,0 @@
fileFormatVersion: 2
guid: f58d25b9e504a4f41ab4a71cf87c1845
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+105
View File
@@ -0,0 +1,105 @@
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.LowLevel;
// Unity 內建輸入 vs Raw Input 對照工具 (開發用,不要放進正式場景)
// 同一段滑鼠移動,同時用兩條路徑收事件 : Unity Input System 的逐筆事件 (eventPtr.time) 與 RawMouseInput (QPC 時間戳)
// 掛在 Test 場景的任一物件上,移動滑鼠幾秒後按 F10,桌面會出現 unity_probe.csv 與 raw_probe.csv,給 Tools/plot_input_histogram.py 畫圖 3.4
public class InputCompareProbe : MonoBehaviour
{
[Tooltip("按 F10 存檔時保留最近幾秒")]
public float keepSeconds = 10f;
private struct Ev { public double t; public float dx, dy; }
private readonly List<Ev> unityHistory = new List<Ev>();
private readonly List<Ev> rawHistory = new List<Ev>();
private int unityThisSecond, rawThisSecond, unityPerSecond, rawPerSecond;
private float secondTimer;
private string saveMessage = "";
void OnEnable()
{
// 預設 Input System 會把同一幀內的滑鼠事件合併成一筆,關掉才拿得到每一筆
InputSystem.settings.disableRedundantEventsMerging = true;
InputSystem.onEvent += OnInputEvent;
}
void OnDisable()
{
InputSystem.onEvent -= OnInputEvent;
}
void OnInputEvent(InputEventPtr eventPtr, InputDevice device)
{
if (!eventPtr.IsA<StateEvent>() && !eventPtr.IsA<DeltaStateEvent>()) return;
if (!(device is Mouse mouse)) return;
if (!mouse.delta.ReadValueFromEvent(eventPtr, out Vector2 delta)) return;
if (delta == Vector2.zero) return; // 只算有位移的回報,跟 Raw Input 一樣
unityHistory.Add(new Ev { t = eventPtr.time, dx = delta.x, dy = delta.y });
unityThisSecond++;
}
void Update()
{
foreach (RawMouseInput.Event e in RawMouseInput.FrameEvents)
{
rawHistory.Add(new Ev { t = e.t, dx = e.dx, dy = e.dy });
rawThisSecond++;
}
double cut = Time.realtimeSinceStartupAsDouble - keepSeconds;
Trim(unityHistory, cut);
Trim(rawHistory, cut);
secondTimer += Time.unscaledDeltaTime;
if (secondTimer >= 1f)
{
unityPerSecond = unityThisSecond; rawPerSecond = rawThisSecond;
unityThisSecond = rawThisSecond = 0; secondTimer = 0f;
}
if (Keyboard.current != null && Keyboard.current.f10Key.wasPressedThisFrame) Save();
}
static void Trim(List<Ev> list, double cut)
{
int remove = 0;
while (remove < list.Count && list[remove].t < cut) remove++;
if (remove > 0) list.RemoveRange(0, remove);
}
void Save()
{
string desktop = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);
Write(Path.Combine(desktop, "unity_probe.csv"), unityHistory);
Write(Path.Combine(desktop, "raw_probe.csv"), rawHistory);
saveMessage = $"已存 Unity {unityHistory.Count} 筆、Raw {rawHistory.Count} 筆到桌面";
}
static void Write(string path, List<Ev> list)
{
StringBuilder sb = new StringBuilder("t,dx,dy\n");
foreach (Ev e in list)
{
sb.Append(e.t.ToString("F6", CultureInfo.InvariantCulture)).Append(',')
.Append(e.dx.ToString(CultureInfo.InvariantCulture)).Append(',')
.Append(e.dy.ToString(CultureInfo.InvariantCulture)).Append('\n');
}
File.WriteAllText(path, sb.ToString());
}
void OnGUI()
{
float y = Screen.height - 80;
GUI.Box(new Rect(10, y - 5, 640, 80), "");
GUI.Label(new Rect(20, y, 620, 22), $"Unity Input System : {unityPerSecond} 筆/秒 Raw Input : {rawPerSecond} 筆/秒 ({RawMouseInput.Status})");
GUI.Label(new Rect(20, y + 20, 620, 22), $"保留最近 {keepSeconds:F0} 秒 : Unity {unityHistory.Count} 筆、Raw {rawHistory.Count} 筆");
GUI.Label(new Rect(20, y + 40, 620, 22), string.IsNullOrEmpty(saveMessage) ? "移動滑鼠幾秒後按 F10 存到桌面 (unity_probe.csv / raw_probe.csv)" : saveMessage);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8295b3ab5b13e99469d2aa0dda56b5f9
Binary file not shown.
+49
View File
@@ -0,0 +1,49 @@
# -*- coding: utf-8 -*-
# 圖 3.4 : Unity 內建輸入 vs Raw Input 的相鄰回報時間間隔直方圖
# 用法 : python plot_input_histogram.py <unity_probe.csv> <raw_probe.csv> [輸出.jpg] [滑鼠回報率Hz]
# 兩個 csv 來自 InputCompareProbe (Test 場景按 F10 存到桌面),欄位 t,dx,dy
import sys, os
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import font_manager
for name in ['Microsoft JhengHei', 'Noto Sans CJK TC', 'PingFang TC', 'Microsoft YaHei']:
if any(f.name == name for f in font_manager.fontManager.ttflist):
plt.rcParams['font.family'] = name; break
plt.rcParams['axes.unicode_minus'] = False
unity_path, raw_path = sys.argv[1], sys.argv[2]
out = sys.argv[3] if len(sys.argv) > 3 else os.path.join(os.path.dirname(os.path.abspath(unity_path)), 'fig3_4_input_histogram.jpg')
hz = float(sys.argv[4]) if len(sys.argv) > 4 else None
def gaps_ms(path):
t = np.loadtxt(path, delimiter=',', skiprows=1, usecols=0, ndmin=1)
t = np.sort(t)
return np.diff(t) * 1000.0
data = [('Unity Input System(引擎內建)', gaps_ms(unity_path)), ('Windows Raw Input(本研究)', gaps_ms(raw_path))]
lo, hi = 1e-3, 50.0
bins = np.logspace(np.log10(lo), np.log10(hi), 80)
fig, axes = plt.subplots(1, 2, figsize=(9, 3.6), sharey=True)
for ax, (title, g) in zip(axes, data):
g = np.clip(g, lo, hi)
w = np.full(len(g), 100.0 / len(g)) # 縱軸 : 佔所有相鄰回報的百分比
ax.hist(g, bins=bins, weights=w, color='#4C78A8', edgecolor='white', linewidth=0.3)
ax.set_xscale('log'); ax.set_xlim(lo, hi); ax.grid(alpha=0.3, which='both', linewidth=0.5)
ax.set_title(title, fontsize=11); ax.set_xlabel('相鄰回報的時間間隔 (ms,對數刻度)')
med = np.median(g); near0 = 100.0 * (g < 0.01).mean()
ax.axvline(med, color='#333333', linestyle='--', linewidth=1)
ax.text(0.98, 0.95, f'事件數 {len(g) + 1:,}\n中位數 {med:.3f} ms\n< 0.01 ms 的比例 {near0:.0f}%',
transform=ax.transAxes, ha='right', va='top', fontsize=9,
bbox=dict(boxstyle='round,pad=0.4', facecolor='white', edgecolor='#999999', linewidth=0.6))
if hz:
ax.axvline(1000.0 / hz, color='#D62728', linestyle=':', linewidth=1)
ax.text(1000.0 / hz, ax.get_ylim()[1] if ax.get_ylim()[1] > 0 else 1, f' 1/{hz:.0f} Hz', color='#D62728', fontsize=8, va='top')
axes[0].set_ylabel('佔比 (%)')
fig.tight_layout(); fig.savefig(out, dpi=200); plt.close(fig)
print('已存', out)
for title, g in data:
print(f'{title} : 事件 {len(g) + 1},中位數 {np.median(g):.3f} ms,< 0.01 ms {100 * (g < 0.01).mean():.1f}%,10%~90% {np.percentile(g, 10):.3f}~{np.percentile(g, 90):.3f} ms')