Publish current live selection and graphics source with external keys

This commit is contained in:
0xcjy
2026-10-02 12:07:33 +08:00
parent 737d34db87
commit d6efc31917
56 changed files with 16917 additions and 1788 deletions
+6
View File
@@ -105,5 +105,11 @@ global-metadata*.dat
*.pfx
*.p12
# Local agent instructions and internal handoff plans
/AGENTS.md
/CLAUDE.md
/implementation_plan.md
/docs/CLAUDE_LIVE_HANDOFF.md
# Handwritten tool project; Unity-generated root IDE projects stay ignored
!/tools/TargetMethodLookup/TargetMethodLookup.csproj
-408
View File
@@ -1,408 +0,0 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
UmaViewer is a Unity application (2022.3.62f1) that loads and displays assets from Uma Musume: Pretty Derby. It reads encrypted asset bundles directly from the game installation without modifying game files.
## Development
**Open the project:** Unity Hub → Add → `C:\Users\riten\Desktop\UmaBuild`
**Run:** Open `Assets/Scenes/Version2` scene → Play in Unity Editor
**Build:** File → Build Settings → PC Standalone → Build
No CLI build commands — Unity Editor is required.
## Game Data & Asset Pipeline
Game assets are encrypted. Key files:
- `meta` (SQLite-MC ChaCha20 encrypted) — maps bundle names → hash filenames in `dat/`
- `dat/{2-char-prefix}/{hash}` — encrypted asset bundles, each with a per-bundle XOR key from meta
**Bundle decryption** (`UmaAssetBundleStream.cs`): header (first 256 bytes) is plain; bytes ≥256 are XOR'd with `FKey = ABKey[i] XOR bundleKey_bytes[j]`.
**meta DB decryption**: `UmaDatabaseController.ReadMetaFromEncryptedDb()` uses `sqlite3mc_x64.dll` with cipher=3 (ChaCha20). Final key = `DBKey[i] XOR DBBaseKey[i % 13]`.
**Asset bundle paths** (key formats):
- Live cutt timelines: `cutt/cutt_son{music_id}/cutt_son{music_id}`
- Live effect prefabs: `3d/effect/live/pfb_{effectName}`
- Stage prefabs: `3d/env/live/live{bgId}/pfb_env_live{bgId}_controller000`
**Python tools** (`tools/`) — rebuilt 2026-08-04 after the old `UmaCrack\` toolchain was deleted. Run with `~/.venvs/umatools/bin/python3` (needs `UnityPy` + `apsw-sqlite3mc`, **not** plain `apsw`; see `tools/requirements.txt`).
| Script | Use |
|---|---|
| `uma_common.py` | Library: key constants, `decrypt_bundle_bytes()`, `MetaDb` (path→hash, UnityPy load) |
| `dump_meta.py` | `plain` → `out/meta_plain.db` · `find <LIKE>` · `info <path>` (hash, dat path, deps, `[NOT DOWNLOADED]`) · `songs` |
| `dump_bundle.py` | `list` / `tree` / `json` / `save` / `gameobjects`, `--deps` |
| `dump_cutt_typetree.py` | **Authoritative track schema.** `--fields <song>` · `--tree <field> <song>` · `--sample <field> <song>` · `--groups` |
| `scan_live_tracks.py` | All 59 songs → `out/scan_keys.csv`, `scan_groups.csv`, `scan_summary.txt`, `scan.json` (~21 s) |
Notes: `meta` decrypts via sqlite3mc `PRAGMA cipher='chacha20'` + `PRAGMA hexkey='<64 hex>'` (the `key=x'...'` and `raw:` forms both fail); `VACUUM INTO` re-encrypts the target, so `dump_meta.py plain` copies schema+rows explicitly.
**Cutt bundles ship full TypeTrees, so field names and keyframe counts from these tools are ground truth.** All 70 worksheets across all 59 songs share one 128-field schema — no version drift. Only `son<id>_camera` and `type_01..type_10` carry the trees; the `cutt_son<id>` prefab and `data` bundles are stripped.
**Getting a track's real field name without the dump tools** — Unity matches bundle TypeTree fields by name, case-sensitively. A field whose name doesn't match is never populated (it does *not* become null — Unity initialises every serialised `List<T>` to an empty list, so null-vs-empty tells you nothing). To test a candidate name, declare it on `LiveTimelineWorkSheet` and check whether it receives keys:
```csharp
LiveTimelineWorksheetDiag.Probe(sheet, "candidateFieldName");
```
Unsure about casing? Declare both spellings side by side — only the correct one fills. This is how `WashLightList` (capital W) was confirmed; note upstream katboi01 uses `washLightList`, which never populates.
## Live Timeline Architecture
The Live playback system is in `Assets/Scripts/umamusume/Gallop/Live/`:
```
Director.cs ← singleton, wires everything together
Cutt/
LiveTimelineControl.cs ← dispatches timeline events each frame (~1900 lines)
LiveTimelineWorkSheet.cs ← all track data fields (ScriptableObject)
LiveTimelineDataList/ ← one .cs per track type
UpdateInfo/ ← structs passed to event handlers
StageController.cs ← manages stage GameObjects, StageObjectMap
```
**Track implementation pattern** (repeat for each new track):
1. Add data class in `LiveTimelineDataList/` (extend `LiveTimelineKeyWithInterpolate` for key, add group wrapper implementing `ILiveTimelineGroupDataWithName`)
2. Add `[SerializeField] public List<...> trackList;` to `LiveTimelineWorkSheet`
3. Add `public event Action<TData, TKey> OnUpdateXxx;` in `LiveTimelineControl`
4. Call `AlterUpdate_SimpleListControl(workSheet.trackList, d => d.keys, OnUpdateXxx, _currentFrame)` in `AlterLateUpdate()`
5. Subscribe `_liveTimelineControl.OnUpdateXxx += handler` in `Director.InitializeTimeline()`
**Important:** `LiveTimelineKeyWithInterpolate` already declares `frame`, `attribute`, `interpolateType`, `curve`, `easingType` — do NOT redeclare these in subclasses.
**Stage shader colour channels** (enumerated at runtime via `Shader.GetPropertyType`, confirmed on stage live10149 / song 1177):
| shader | colour | brightness | other |
|---|---|---|---|
| `Gallop/3D/Live/Stage/DefaultNoAmbient` | `_MulColor0` | `_ColorPower` | |
| `Gallop/3D/Live/Stage/DefaultEnvMapNoAmbient` | `_MulColor0` | `_ColorPower` | `_AddColor`, `_EnvMap` |
| `Gallop/3D/Live/Stage/DefaultTransparentNoAmbient` | `_MulColor0` | `_ColorPower` | `_AmbientColor` |
| `Gallop/3D/Live/Stage/LightBlinkBlend` | `_BlinkLightColor` | `_ColorPower` | `_SrcBlend`/`_DstBlend` |
| `Gallop/3D/Live/Stage/LightBlend` / `LightAdd1` | `_MulColor0`, `_MulColor1` | `_ColorPower`, `_ColorPowerMultiply` | |
| `Gallop/3D/Live/Stage/Laser` | `_MulColor0`, `_MulColor1` | `_ColorPower` | `_RandomValue` |
| `Gallop/3D/Bg/BgMirrorBall` | `_MulColor0` | **(none)** | |
| `Gallop/3D/Live/Stage/StageMirrorBallShine` | (none) | | |
| `Gallop/3D/Live/Stage/StageTransmittedLightMask` | (none) | | `_TransmittedLightMaskScale` |
**Brightness is a separate channel — do not fold it into the colour.** Write the key's colour to the colour property and its `power` to `_ColorPower`; let the shader combine them. Only fall back to `colour * power` where `_ColorPower` is absent (`BgMirrorBall`).
**Writing shader properties: one shared block, always Get → modify → Set.** All of `Director`'s
handlers write through the single `PropBlock` (`Director._propBlock`) and must call
`renderer.GetPropertyBlock(block)` first — `SetPropertyBlock()` **replaces** the block rather than
merging, so a handler that starts from an empty block wipes whatever another track wrote to the
same renderer earlier in the same frame. That is exactly how GlobalLight was silently dead for
59/59 songs (BgColor1's character branch runs right after it and cleared all 13 rim properties).
Never `new MaterialPropertyBlock()` per frame, and never write `_Color` without first checking the
target shader's real property table — three separate tracks shipped no-op colour writes that way.
Dump any shader's real property table with:
```python
# tools/, via ~/.venvs/umatools/bin/python3
env = MetaDb().load("shader") # 499 shaders
pf = obj.read_typetree()["m_ParsedForm"] # m_Name, m_PropInfo.m_Props
```
**`_MulColor0` is on every stage shader and is BgColor1's channel; `_AmbientColor` belongs to BgColor2.** They are separate properties on the same shader, so the two tracks must not write the same one. Same naming family as WashLight's `MulColor0` and UVScrollLight's `mulColor1`.
⚠️ A material's `m_SavedProperties` in the bundle lists properties it no longer has — it retains entries from whatever shader it was authored against. `Material.HasProperty()` asks the *current shader*. Always enumerate the shader, never trust the bundle's saved-property table.
**渲染状态也从这张过期表里读,后果最严重。** Gallop 的发光类 shader 把混合写成
`Blend [_SrcBlend] [_DstBlend]`,也就是**从材质属性取渲染状态**。live10149 的
**26/26 个材质**存的都是 `_SrcBlend=One, _DstBlend=Zero`(不透明覆盖),且每一个的 float 表里
都带着 `_WorkflowMode`/`_Surface`/`_ClearCoatMask`/`_Smoothness`/`_Blend` —— 那是 **URP Lit
的属性表**,整批盖上去的,One/Zero 正是 URP Lit 的不透明预设。
作者意图可查:全库 16 个声明这两个属性的 shader 里,**14 个默认 `One/One`(加法混合)** ——
`LightBlinkBlend`、`LightBlend`、`StageBeamLight{,Cutoff,Fadeout}`、
`StageLightBlink{Cutoff,Fadeout}`、`StageProjectorBlend{,VertexAlpha,AnimVertexAlpha}`、
`StageMonitorBlend*`、`MirrorBallProjector`、`BgUnlitStencilAlpha`,全是发光/投影那一批。
被压成不透明后,加法光柱「颜色为黑 = 什么都不加 = 不可见」变成了**一堵实心黑墙**。
⚠️ **实际受害面比存档表窄得多,别照着 26 这个数推。** 只有**当前 shader 真的声明了**这两个
属性的材质才会被读到;其余材质虽然也存着 `One/Zero`,但那只是过期条目,无人问津。
live10149 实测(`[StageBlend]` 日志):31 个材质里**只有 1 个**被修正 ——
`mtl_env_live10149_blinklight000` / `LightBlinkBlend`,`_DstBlend` 0 → 1。
**但「1 个材质」严重低估了影响面 —— 材质在舞台上是高度共享的。** 那一个材质铺满
27 个 BlinkLight 组、约 **1450 个渲染器**(观众席 95、mob000 570、glow_object 67、
glow_ramp 58、镜面球闪片 83、全部 wash 组、各种 LED 板),实机确认修好的不只是地面 wash 灯的
黑楔子,长期挂着的「小灯泡渲染成黑块」也一并正常了。
**教训(第三次同一天):报数要报对单位。** 舞台上约 1500 个渲染器只有 31 个材质,
按材质计数会把影响面说小两个数量级 —— `[StageBlend]` 日志现在同时报渲染器数。
`StageController.RestoreAuthoredBlendState()` 在舞台初始化时把这两个属性写回 **shader 声明的
默认值**(`Shader.GetPropertyDefaultFloatValue`),对本来就该不透明的 shader 是空操作,自限。
改了哪些材质会逐条打进 `[StageBlend]` 日志。
> 教训比这个 bug 本身通用:**过期存档表不只影响颜色,还能改渲染状态**。
> 看到「本该发光的东西是黑的/挡住后面的东西」,先查 `_SrcBlend`/`_DstBlend`,
> 再查颜色写对没有。
Worked example — `mtl_env_live10149_projector001` (shader `Gallop/3D/MirrorAndShadow/MirrorBallProjector`, 22 real properties) saves 40+, including Standard-shader leftovers (`_Glossiness`, `_Metallic`, `_Parallax`, `_Mode`, `_UVSec`) **and** four plausible-looking ghosts the current shader never declares: `_IsLoopYRotation`, `_LoopYRotationSpeed`, `_MirrorBallProjectionIntensity`, `_MirrorBallRotateWS`. Two of those are older spellings of properties that *do* exist (`_MirrorBallIsLoopRotation`, `_MirrorBallLoopRotationSpeed`) — exactly the kind of near-miss that reads as a discovery. Note also that where a component field and a saved property disagree (`MirrorBallFallOffPower` = 1.0 on the component vs `_MirrorBallFalloffPower` = 2.0 in the material), the component wins at runtime: these controllers push their own fields into the material.
**Track group names are not always GameObject names.** Four separate silent failures were traced to this in one session, so check the mapping before assuming a track is unimplemented:
- a whitelist filter in the dispatcher dropped 92% of BgColor1's keys (`validBgColorNames`)
- `StageObjectMap` dedupes by name, so a crowd of 66 same-named objects only ever got its first member
- the Object track's `neonsign` is a `_stageObjectUnits` **unit name**, not a GameObject — no object of that name exists
- `ObjectUpdateInfo.OffsetType` was populated by the dispatcher but never read by `StageController`, so `Add`-relative positions were written as absolute
All four failed silently, with no error. Treat a track that "works" but looks wrong as a routing problem first.
**StageObjectMap:** Stage child GameObjects are indexed by name. Objects whose names match `IsTimelineControlledLight()` (`blinklight`, `spotlight3d`, `_wash_`, `laser`) start `SetActive(false)` — their handlers call `SetActive(true)` when the track fires. All other objects (neonsigns, glow meshes, UV scroll objects, etc.) keep their prefab default state.
## Ground-truth sources: what is recoverable and what is not
Mapped 2026-08-05. **Check this list before declaring something "unknown"** — several things
previously written off as un-reversible are in fact dumpable, and one whole class of problem
was solved by realising the game's own scripts can be re-bound.
### Available
| 来源 | 给出什么 | 怎么取 |
|---|---|---|
| cutt bundle TypeTree | 128 个轨道字段名 + 全部关键帧值,59 首全带 | `tools/dump_cutt_typetree.py` |
| 舞台 prefab TypeTree | GameObject 层级、组件构成,**以及缺失脚本 MonoBehaviour 的字段名和值**(离线可读) | `MetaDb().load('3d/env/live/liveNNNNN/pfb_..._controller000')` |
| shader bundle | 499 个 shader 的真实属性表(名/类型/默认值/range) | 枚举 `m_ParsedForm.m_PropInfo.m_Props` |
| material bundle | 材质的 shader 绑定与存档属性(⚠ 存档表含过期条目,见下) | `sourceresources/3d/env/live/liveNNNNN/materials/mtl_*` |
| AnimationClip | 曲线的 path / 目标属性 / 关键帧时间与值 | `m_RotationCurves` 等 |
| MonoScript | **类名 + namespace + 程序集名** | 见下,这是最重要的一条 |
### ⭐ 用原签名重建脚本,可直接拿到真实序列化字段
舞台 prefab 引用了 11 个脚本类,UmaViewer 起初只实现了 `StageController`,其余 892 个
MonoBehaviour 实例脚本为空。**但这些脚本是可以「接管」的** —— Unity 按
**类名 + namespace + 程序集名** 解析 MonoScript,而 `Assets/Scripts/umamusume.asmdef`
的程序集名正是 bundle 里写的 `umamusume`。所以只要按签名建类,字段就会被真正反序列化进来。
已验证:新建 `Gallop.Live.BillboardController` 后,`[StageScripts]` 的「脚本丢失」
从 **892 降到 728**(正好 −164 个实例),`_rotationType` 等字段直接可读。
签名清单(`Assets/Scripts/` 下任意位置均可,只要在 umamusume 程序集内):
| namespace | 类 | live10149 实例数 | 状态 / 已 dump 到的字段 |
|---|---|---|---|
| `Gallop.Live` | `AnimationObjectController` | 282 | ❌ **别建,建了也没用**:实测序列化字段 **一个都没有**(282 个实例全空)。重建只会让「脚本丢失」892→446,拿到 0 bit 新信息 —— 它是纯行为类,播哪个 clip / 何时播 / 多快全在拿不到的方法体里。顶替版已于 2026-08-07 撤除,舞台 Animation 现在**有意不播**,见下 |
| `Gallop.Live` | `UnityLensFlareController` | 205 | ❌ 只有 1 个字段 `_enableAngleDegree`(0),本体不在这里 |
| `Gallop.Live` | `BillboardController` | 164 | ✅ 已建(字段已读到,朝向行为待定)|
| `Gallop.Live` | `WashLightController` | 27 | ❌ 24 个字段全是具体数值 + 两张投影贴图(`_projectionTexture`/`_cameraProjectionTexture`),缺的是 URP 下的投影实现 |
| `Gallop.Live` | `LightProjection` | 4 | ❌ 只有 `_projectionType`(1) |
| `Gallop.RenderPipeline` | `CustomLensFlare` | 200 | ❌ **数据最完整、最值得做的一个**,见下 |
| `Gallop.RenderPipeline` | `MirrorBallProjector` | 4 | ❌ 字段已 dump 但**运行时绑定不可见**,见 Blocked |
| `Gallop.RenderPipeline` | `CustomProjector` | 4 | ❌ 就是一套 legacy `Projector` 参数(near .1 / far 60 / fov 30 / aspect 1 + `Material`)|
| `Gallop` | `MirrorReflection` | 1 | ✅ 已建并实现(平面镜反射,见下)|
| `Gallop.Live.ShaderParam` | `ShaderParamController` | 1 | ⚠ **不值得做**:实测只有 `_AmbientColor`/`_CharaColor` 两个向量,值都是 (1,1,1,1),实现出来是空操作 |
**LensFlare 这条线数据是齐的**(这也是目前性价比最高的一块):
- `CustomLensFlare` 字段:`Flare`(PPtr) / `Brightness` / `FadeSpeed` / `Color` / `IgnoreLayers` / `IsDirectional`。
- `Flare` 指向的**不是** Unity 内置 `Flare` 资产,而是 `Gallop.RenderPipeline.LensFlareData`
这个 ScriptableObject(同样在 umamusume 程序集里,照样可以按签名重建)。
路径形如 `sourceresources/3d/env/live/common/lensflare/flare013/flares/flare013_00`。
- 它的字段是 Unity legacy Flare 的逐字翻版:
`TextureLayout` / `Texture` / `ElementArray[{ImageIndex, Position, Size, Color, UseLightColor,
Rotate, Zoom, Fade}]` / `UseFog`。**所以语义不受 IL2CPP 阻塞** —— 这些是 Unity 自己的概念。
- live10149 上 199 个物件同时挂 `CustomLensFlare` + `UnityLensFlareController` + MeshRenderer,
另有 5 个只挂 `UnityLensFlareController`。舞台上**没有任何 legacy `LensFlare` 组件**,
原版是自己画的。URP 侧对应物是 `LensFlareComponentSRP` + `LensFlareDataSRP`。
字段名必须和 TypeTree 逐字一致(大小写敏感),dump 一下即可。
这条同样适用于任何其它 bundle 里的 MonoBehaviour。
**重建签名只拿得到数据,拿不到方法体。** 两个已建的类正好是两种情形:
- `MirrorReflection`(`Assets/Scripts/umamusume/Gallop/MirrorReflection.cs`)—— 接收端能
自己查出来,所以能补完行为:宿主 `mirror_a` 的材质用 `Cygames/MirrorAndShadow/ReceiveMirror`,
该 shader 只有 `_MainTex`/`_ReflectionTex`/`_Color`/`_ReflectionRate`,而组件字段
`_mirrorReflectionColor`/`_mirrorReflectionRate` 与后两者逐字对应。实现方式是第二摄像机
+ 反射矩阵 + 斜投影渲进 RT 再写回 `_ReflectionTex`(URP 下不能用 `Camera.Render()`,
必须挂 `beginCameraRendering` 拿 `ScriptableRenderContext` 后 `RenderSingleCamera`)。
这同时解决了长期的「地板发白」——`_ReflectionTex` 未绑定时 Unity 代入白贴图,
而 `_ReflectionRate` 默认 1.0,等于满强度白反射。
- `BillboardController` —— 字段读到了,**但行为写了一版又关掉了**,这是「重建签名」的能力边界。
`_rotationType == 0` 是不是「整轴朝向摄像机」、朝向该用摄像机 up(跟镜头 roll)还是世界 up
(只绕 Y),都没有 ground truth;实机看是「一直转来转去,而那东西不该转」,
于是 `BillboardController.EnableRotation` 默认 false,面片保持 prefab 作者摆好的朝向。
同一次排查里揪出一个**确定的** bug(已修):目标摄像机只解析了一次就缓存,
而生效摄像机随 CameraSwitcher 每帧变 —— 切换后面片朝的是观众看不见的那台,
那台还在自己动,看上去就是无缘无故乱转。**凡是引用「当前摄像机」的舞台脚本都要注意这条。**
**舞台自带 Animation 有意不播**(283 个组件,2026-08-07 撤除了替代实现):
它们全部 `playAutomatically = true` 但默认 clip 为空,原版靠 `AnimationObjectController`
显式 `Play()`,而那个类**零序列化字段**,纯行为,方法体拿不到 —— 「播哪个 / 何时播 / 多快」
没有任何数据能还原。写过一版 `StageAnimationPlayer` 顶替,策略是「只有一个 clip 就播」,
错在把「这物件只有一个**状态**」当成「这个状态**一直在播**」(后者正是那个缺失的类每帧做的
决定):wash 灯 2 秒一个来回疯狂摆头(原版不扫只闪),镜面球转速无从校验。已整体撤除。
**完整理由与复活条件见 `LIVE_TRACKS.md` →「舞台自带 Animation 为什么不播」专条。**
⚠ 撤除时唯一保留下来的结论:**驱动舞台动画不要用 `Animation.Play()`**,
那跑 Unity 自己的时钟,暂停/拖动进度条都会脱节;应每帧把 `AnimationState.time` 设成
`LiveTimelineControl.currentLiveTime`(秒)再 `Sample()`。将来重做直接用这条。
### 🔎 舞台上「行为不对」的第一嫌疑:缺组件,不是解析错
**这是分诊规则,不是某一次的结论。** 舞台 prefab 引用 11 个脚本类,至今仍有 **728 个
MonoBehaviour 实例是空的**(基线 892,已补 `BillboardController` −164)。其中
`AnimationObjectController` 一家就占 282 个实例 —— 舞台上所有「什么时候动、动多快、
动哪一个」的决定原本都在它手里,而它整个不存在。
所以当某个舞台元素表现不对(该动的不动、不该动的在动、动的节奏不对),
**默认假设应该是「原版那个组件缺失,现在由我们猜的行为顶着」,而不是「数据解析错了」**。
理由是可检验的:字段值、clip 曲线、shader 属性表这些**数据**层面的东西全都能 dump 出来核对,
而且一路核对下来**基本都是对的**;反复出错的是**行为**层面 —— 那正好是拿不到方法体的部分。
已经有两个同形状的例子,都是「物件选对了、行为猜错了」:
| 现象 | 数据对不对 | 真实原因 |
|---|---|---|
| wash 灯疯狂摆头 | clip 曲线完全正确(实测 90°→0°→90°) | 缺 `AnimationObjectController`,我们替它决定了「一直播」 |
| 面片一直乱转 | 字段全部正确读到 | 缺原方法体,`_rotationType==0` 的语义是我们猜的 |
推论一:动手前先查一眼**这个物件挂过什么脚本、那个脚本我们有没有**
(`[StageScripts]` 日志 + `CLAUDE.md` 的签名清单),比直接怀疑解析快得多。
推论零:**先 dump 一眼那个缺失组件有没有字段,再决定值不值得重建。**
`AnimationObjectController` 实测**零字段**(282 个实例全空),所以重建它拿不到任何信息,
舞台动画的那些时机问题不可能靠「把原类建出来」解决 —— 这个方向是死的,
别再试。反过来 `CustomLensFlare` 字段齐全(还牵出 `LensFlareData`),就非常值得建。
判断只要一条命令,不要凭实例数多就以为收益大。
推论二:**顶替缺失组件时,要把「我在替谁做决定」写清楚**,并且区分
「从 bundle 数据推出来的」和「看参考视频观察到的」—— 后者是有效证据,但不是 ground truth,
换个舞台可能就不成立。(反面教材:舞台动画的 `_wash_` 排除规则就是这么来的,
后来连同整个替代实现一起撤掉了 —— 观察能证伪一个实现,但支撑不起一个实现。)
反例也要记住:**并非所有舞台画面问题都是缺组件。** 光柱渲染成黑墙那次,
根因是材质被盖了 URP Lit 的属性表、`_DstBlend` 从 One 变成 Zero,
把加法混合压成了不透明 —— 那是**数据**问题,而且是 dump 得出来的(见下)。
分诊规则的意思是「先查缺不缺组件」,不是「一律归咎于缺组件」。
### Blocked
**IL2CPP 元数据拿不到。** 游戏是 IL2CPP 构建,但 `global-metadata.dat` 既不在
`umamusume_Data/il2cpp_data/`(那里只有 `Resources/`),也没嵌在 `GameAssembly.dll` 里
—— 魔数 `0xFAB11BAF` 零命中,`BillboardController` / `_rotationType` 等标识符字符串
也全部搜不到。这是该游戏已知的反篡改,元数据运行时才还原。
因此以下**永远拿不到标准答案**,只能靠交叉验证或承认未知:
- **游戏自己定义的枚举语义** —— `_rotationType`(0/2)、`LightBlendMode`、`CmnColorType0/1`、
BlinkLight 的 `pattern`、`ColorType` 等。字段值读得到,含义读不到。
⚠ 但**先分清是谁的枚举**:`LensFlareData.TextureLayout` 长得像这一类,其实是 Unity
legacy `Flare` 资产的 `FlareTextureLayout`,语义在 Unity 侧公开,不受此限。
- **对象之间的运行时绑定** —— 重建签名只能拿到**数据**,拿不到原方法体,所以「这个组件
跑起来去找谁」是不可见的。实例:`MirrorBallProjector` 的 shader 需要
`_MirrorBallPosWS`/`_MirrorBallScale`/`_MirrorBallRotateValue`,而组件里**没有任何指向
灯球的引用字段**,4 个 projector 全在原点、共用同一个材质,灯球却散布在 6 个位置。
绑定关系只存在于方法体里。
- **速度/系数一类的常量** —— 如果原版在代码里对动画做了调速,那个倍率无从得知。
(注意这条不要滥用:镜面球转速一度被记成此类,实测其实完全确定,见下。)
- 未随包发布的 shader(PostFilm 的定义性 shader 就在 app 二进制里)。
**「灯球转速」到底确定到什么程度(2026-08-07,当天两次修正)**
⚠️ **先说结论的边界**:clip 里的转速是硬数据,**但「原版按 1.0 倍速播这条 clip」不是**。
实机跑下来观察是「所有迪斯科灯球还是太快」,也就是说原版多半有个播放倍率或者压根不用
这条 clip 驱动球体 —— 那正是本节上面「速度/系数一类的常量」说的那类不可知量。
下面的数字只证明「**我们忠实地播了这条 clip**」,不证明「和原版一致」。
已确定的部分:
- live10149 的 4 个 `MirrorBallProjector` 实例**全部** `MirrorBallIsLoopRotation = 0`、
`MirrorBallLoopRotationSpeed = 0`、`MirrorBallLoopRotationValue = 0` ——
shader 自带的 loop-rotation 通路在这个舞台上是**关掉的**,不是转速来源。
- 真正在转的是 clip `anm_env_live10149_blinklight_mirrorball_flarelight_loop_000`:
6 条 quaternion 曲线(`mirrorball_a_000` + `b_000..004`),7 个关键帧,
**恒定 −179.50°/s 绕 Y**(每个关键帧算出来都是这个数),2.0 s 一圈,wrapMode = Loop。
末帧 −359° 而不是 −360°,是为了循环接缝不重复一帧。
- 曾接管过这条 clip,采样用的 `currentLiveTime` 单位是秒(帧号 = ×60),**没有单位换算错误**,
放出来就是 clip 写的 2.0 s 一圈 —— 但实机仍然偏快,这正是下面第 2 条教训的由来。
该实现已于 2026-08-07 撤除,球现在不转。
两条教训,方向相反,都要记:
1. 把「值是 0」当成「值未知」是两回事 —— dump 之前先看一眼开关字段
(`MirrorBallIsLoopRotation` 就是那个开关)。
2. **但「clip 的转速是确定的」推不出「转速问题解决了」**。我上一版文档写成了
「我们的构建里转速本来就是对的」,实机观察当天就否掉了它。
数据确定的是**素材**,不是**原版怎么用这个素材**;中间那个倍率仍然是不可知量。
### ⚠ 现象描述不是 ground truth
字段值、shader 属性表是硬数据;**「哪个物件看起来不对」不是** —— 文档里的现象描述往往
没经过验证。地板发白排查栽在这上面:文档记着 `plane_000` / `stage_object_001` /
`specular_002` 发白,整轮排查都围着这三个转,最后查明白的其实是**叠在同一位置的
`mirror_a`**(同在 `pfb_env_live10149_main000` 下、局部变换全为单位,肉眼分不出)。
它用 `Cygames/MirrorAndShadow/ReceiveMirror`,`_ReflectionRate` 默认 1.0 而
`_ReflectionTex` 从没赋值 —— Unity 对未绑定采样器代入白贴图,满强度白反射。
期间那个「把 `_EnvRate` 归零无变化」的实验因此也是误导:切的是另一批物件。
**排查视觉问题的第一步应该是确认现象归属于哪个物件**(让代码把可疑物件隔离/高亮),
而不是从文档里的名字出发。
### 间接手段(已被证明有效)
拿不到直接答案时,**相关性交叉验证**多次奏效,比猜测可靠得多:
- BlinkLight 调色板槽位规则:靠「物件名 `lightNNN_`/`alphaNNN_` 前缀的种数」与
「调色板里去重颜色数」在**每一组都精确相等**推出,7 组无一例外。
- BgColor1 的通道 `_MulColor0`:靠枚举 shader 属性表 + 排除法确认。
- 「某属性存在」≠「目标 shader 上有该属性」—— `_Color` 空写连续栽了三次
(BlinkLight / Spotlight3d / UVScrollLight),扫一遍 shader 属性表即可批量排查。
## Working rule: no ground truth, no implementation
Field names, keyframe values and shader property tables are all recoverable from the bundles
(`tools/`), so **verify before you write code** — and when something genuinely cannot be
recovered, leave it unimplemented with a TODO rather than guessing a value.
Guessing has cost real time in this project: the PostFilm vignette geometry was guessed twice
(full-screen wash, then a huge border) before it turned out the defining shader isn't shipped in
any bundle. `PostFilmRendererFeature._enableRendering` is now `false` for exactly this reason.
Note the distinction that has caught me out: *"the property exists"* is not *"this field maps to
that property"*. `_ColorPower` is present on the stage shaders, but there is no evidence that
BgColor1's `power` field drives it — so that write was reverted while BlinkLight's was kept
(there the shader `LightBlinkBlend` is named for the track and pairs `_BlinkLightColor` with
`_ColorPower`, which is a much tighter fit).
Open items and why each is blocked are tracked in `LIVE_TRACKS.md` → 「已知未解问题」.
## Currently Implemented Tracks
| Track | Data class | Notes |
|-------|-----------|-------|
| Camera (pos/lookat/fov/roll/switcher) | existing | fully working |
| CharaMotionSequence | existing | |
| Facial / LipSync / FormationOffset | existing | |
| GlobalLight (48) | existing | sets rim light shader props on characters |
| BgColor1 | existing | **two branches.** Groups named `CharaCenter/CharaLeft/CharaRight/CharaColor` (`LiveTimelineControl.CharaBgColorNames`) → character toon props (`_CharaColor`, `_ToonDarkColor`, …). Every other group name → stage renderers, resolved by walking the whole stage hierarchy for same-named Transforms (`Director.ResolveStageTargets`), writing **`_MulColor0`** via `MaterialPropertyBlock`. |
| BgColor2 | existing | sets `_AmbientColor` on stage renderers via `Lerp(color1, color2, value)` |
| Transform / Object | existing | handled by `StageController.cs` |
| Effect (60) | `LiveTimelineEffectData` | loads prefab from `3d/effect/live/pfb_{name}` |
| GlobalFog (49) | `LiveTimelineGlobalFogData` | sets `RenderSettings.fog*` |
| Spotlight3d (68) | `LiveTimelineSpotlight3dData` | looks up `keyData.assetName` in StageObjectMap |
| UVScrollLight (46) | `LiveTimelineUVScrollLightData` | sets texture UV on stage materials |
| VolumeLight (37) | `LiveTimelineVolumeLightData` | data deserialized, no visual (component absent) |
| LightShafts (50) | `LiveTimelineLightShaftsData` | data deserialized, no visual (component absent) |
| Particle (41) | `LiveTimelineParticleData` | sets ParticleSystem.emission.rateOverTime |
| ParticleGroup (42) | `LiveTimelineParticleGroupData` | sets FlickerLightRate |
| ChromaticAberration (73) | `LiveTimelineChromaticAberrationData` | URP `ChromaticAberration.intensity` ← `power`;per-channel offset 无法映射 |
| HdrBloom (38) | `LiveTimelineHdrBloomData` | **no handler, deliberately** — 0/58 songs carry data (`hdrBloomKeys` empty in every scan and in the song-1177 dump), and the field→URP-`Bloom` mapping was never verifiable. Data layer (data class, worksheet field, event) is kept; the Director handler and the `Bloom` volume override were removed 2026-08-07. |
| ColorCorrection (61) | `LiveTimelineColorCorrectionData` | URP `ColorAdjustments.saturation` + `ColorCurves` RGB;depth/blend curve 无 URP 对应 |
| BlinkLight | `LiveTimelineBlinkLightData` | SetActive + writes `_BlinkLightColor`/`_ColorPower` on the group's renderers (56/58 songs). **Biggest lighting payload by far** — 全语料 19420 keys / 57 songs, and over half are named `*_wash_*` (`wash_truss_a` 147, `wash_truss_b` 147, `wash_ground_a` 51, …). Palette slot = the `lightNNN_`/`alphaNNN_` prefix of the renderer or its nearest ancestor; renderers with no prefix are left to their real owner (BgColor1) when the group has slotted ones. `color1Array` / `LightBlendMode` / `isReverseHueArray` still unused. |
| WashLight | `LiveTimelineWashLightData` | SetActive only (5/58 songs). Low value: real "wash light" output comes from the BlinkLight `*_wash_*` groups above, not this track — song 1177 has just 1 group / 11 keys here. |
| Laser | `LiveTimelineLaserData` | SetActive + position/rotation/scale — blink/raycast not implemented (6/58 songs) |
## Track Coverage (from 58-song scan)
**The pre-2026-08-04 scan data in `LIVE_TRACKS.md` was wrong** and has been re-measured with `tools/`. Two systematic errors: a batch of tracks marked "WorkSheet 无 X 字段" do have the field (`MobControlKeys`, `CyalumeControlKeys`, `nodeScaleList`, `sweatLocatorList`, `monitorCameraPos/LookAtKeys`, `facialNoiseKeys`, `charaMotionNoiseKeys`, …), and a batch marked "全 0 keyframe 空占位" carry thousands of keys (`postFilmKeys`/`postFilm2Keys`/`postFilm3Keys` ≈20 200 keys over 59/59 songs, `radialBlurKeys`, `tiltShiftKeys`, `charaFootLightKeys`, …). Rows tagged ✅实测 are trustworthy; untagged rows are still old data. **Re-verify with `tools/` before acting on any untagged row.**
Coverage numbers measure **what exists in the bundles**, not what the C# consumes — the two diverge. When a track looks under-powered, check the dispatcher in `AlterUpdate_*` for filters before assuming it's unimplemented (BgColor1 was dropping ~92% of its keys that way).
**Measuring what a song actually carries**: `LiveTimelineWorksheetDiag.Dump()` is called from `Director.InitializeTimeline()` and logs, per worksheet, every track field with its group names and key counts. Confirmed on song 1177: `worksheetList.Count == 1`, `SheetType == MainLive`, so reading `worksheetList[0]` loses nothing.
+98 -3
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.Reflection;
using Gallop;
using Gallop.Live;
@@ -54,10 +54,14 @@ public static class LiveDofFocusRegression
bool previousDof = GallopImageEffect.UserDofEnabled;
var root = new GameObject("DofFocusRegression");
root.SetActive(false);
var timelineData = ScriptableObject.CreateInstance<LiveTimelineData>();
timelineData.maxForcalSize = 30f;
var worksheet = ScriptableObject.CreateInstance<LiveTimelineWorkSheet>();
try
{
var director = root.AddComponent<Director>();
var timeline = root.AddComponent<LiveTimelineControl>();
timeline.data = timelineData;
director._liveTimelineControl = timeline;
var cameraObject = new GameObject("DofTestCamera");
cameraObject.transform.SetParent(root.transform);
@@ -84,7 +88,9 @@ public static class LiveDofFocusRegression
dofSmoothness = 0.5f, dofQuality = 1, charactor = 1
};
var update = typeof(Director).GetMethod("OnUpdatePostEffect_Dof", PrivateInstance);
Action apply = () => update.Invoke(director, new object[] { key });
var resolve = typeof(LiveTimelineControl).GetMethod("ResolveDofWorldFocus", PrivateInstance);
Action apply = () => update.Invoke(director,
new[] { (object)key, resolve.Invoke(timeline, new object[] { key }) });
PostImageEffectFeature.ResetRuntimeParameter();
GallopImageEffect.SetUserDofEnabled(true);
apply();
@@ -118,6 +124,44 @@ public static class LiveDofFocusRegression
RequirePreparedFocus(4f);
// A valid focus does not override the author's DOF enable flag (bit18).
// Bit19 is point-ball-blur mode, not permission to turn DOF on.
key.attribute = (LiveTimelineKeyAttribute)0x90000;
apply();
state = PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay;
Require(!state.IsEnableDof && state.UseDofDiffusionBloomType ==
Gallop.ImageEffect.DofDiffusionBloomOverlayParam.DofDiffusionBloomType.DiffusionBloom,
"An authored disabled key must keep the frame sharp while preserving Bloom/Diffusion.");
GallopImageEffect.SetUserDofEnabled(false);
GallopImageEffect.SetUserDofEnabled(true);
Require(!PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay.IsEnableDof,
"The user toggle must not resurrect author-disabled DOF while paused.");
key.attribute = (LiveTimelineKeyAttribute)0x50000;
apply();
Require(PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay.IsEnableDof,
"The next authored enabled key must restore positional DOF.");
// Explicit render auto state, not the unrelated source constructor default.
PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay.IsEnableDofAutoDisable = true;
key.forcalSize = 29f;
apply();
Require(PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay.UseDofDiffusionBloomType ==
Gallop.ImageEffect.DofDiffusionBloomOverlayParam.DofDiffusionBloomType.DiffusionDofBloom,
"Size29 below the authored30 threshold must remain a DOF render mode.");
key.forcalSize = 30f;
apply();
Require(PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay.UseDofDiffusionBloomType ==
Gallop.ImageEffect.DofDiffusionBloomOverlayParam.DofDiffusionBloomType.DiffusionBloom,
"Equality to the authored threshold must bypass only DOF.");
timelineData.maxForcalSize = 31f;
apply();
Require(PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay.UseDofDiffusionBloomType ==
Gallop.ImageEffect.DofDiffusionBloomOverlayParam.DofDiffusionBloomType.DiffusionDofBloom,
"Changing the authored threshold must release temporary disable, not retain size history.");
timelineData.maxForcalSize = 30f;
PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay.IsEnableDofAutoDisable = false;
apply();
// Invalid target bypasses only DOF, rather than falling back to 1m.
SetProperty(timeline, "HasDofCameraLookAt", false);
apply();
@@ -136,11 +180,62 @@ public static class LiveDofFocusRegression
state = PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay;
Require(state.IsEnableDof && state.DofFocalType == DepthBlurAndBloom.DofFocalType.Position,
"Re-enabling while paused must restore positional focus.");
Debug.Log("[LiveDofFocusRegression] PASS: startup look-at, metric focus, camera cut, missing target, depth request, prepared focal depths/sharp intervals, DOF gate, paused restore.");
// The NEXT key owns interpolation; focus endpoints have independent flags.
Set(timeline, "_liveStageCenterPos", new Vector3(4f, 1f, 12f));
worksheet.postEffectDOFKeys = new LiveTimelineKeyPostEffectDOFDataList();
worksheet.postEffectDOFKeys.thisList.Add(key);
worksheet.postEffectDOFKeys.thisList.Add(new LiveTimelineKeyPostEffectDOFData
{
frame = 60, attribute = (LiveTimelineKeyAttribute)0x20000, charactor = 0,
forcalSize = 10f, dofFocalPoint = 8f, dofQuality = 5,
interpolateType = LiveCameraInterpolateType.Curve,
curve = AnimationCurve.Linear(0f, 1.25f, 1f, 1.25f)
});
timeline.OnUpdatePostEffect_Dof += (sample, world) =>
update.Invoke(director, new object[] { sample, world });
typeof(LiveTimelineControl).GetMethod("AlterUpdate_PostEffect_Dof", PrivateInstance)
.Invoke(timeline, new object[] { worksheet, 30 });
state = PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay;
Require(state.DofFocalType == DepthBlurAndBloom.DofFocalType.Position &&
state.DofFocalPosition == new Vector3(4.75f, 0.75f, 14f),
"Mixed look-at/character targets must interpolate world focus without changing the current coordinate mode.");
Require(Mathf.Approximately(state.DofFocalSize, 5f) && state.IsEnableDof,
"An overshooting next curve must retain signed, unclamped sampling and the current enable flag.");
apply();
// Real Live subtype owns auto-disable; a plain/helper adapter must not inherit it.
var liveCameraObject = new GameObject("LiveDofTestCamera");
liveCameraObject.transform.SetParent(root.transform);
var liveCamera = liveCameraObject.AddComponent<Camera>();
var liveEffect = liveCameraObject.AddComponent<LiveImageEffect>();
liveEffect.DofDiffusionBloomOverlayParam.IsEnableBloom = true;
liveEffect.DofDiffusionBloomOverlayParam.IsEnableDiffusion = true;
Set(director, "_cameraObjects", new[] { camera, liveCamera });
Set(director, "_activeCameraIndex", 1);
key.forcalSize = 30f;
apply();
Require(PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay.UseDofDiffusionBloomType ==
Gallop.ImageEffect.DofDiffusionBloomOverlayParam.DofDiffusionBloomType.DiffusionBloom,
"Live initialization must make a threshold-wide shot sharp without removing Bloom/Diffusion.");
key.forcalSize = 1f;
apply();
Require(PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay.UseDofDiffusionBloomType ==
Gallop.ImageEffect.DofDiffusionBloomOverlayParam.DofDiffusionBloomType.DiffusionDofBloom,
"A Live close-up below the authored threshold must still render DOF.");
Set(director, "_activeCameraIndex", 0);
key.forcalSize = 30f;
apply();
Require(PostImageEffectFeature.RuntimeParameter.DofDiffuionBloomOverlay.UseDofDiffusionBloomType ==
Gallop.ImageEffect.DofDiffusionBloomOverlayParam.DofDiffusionBloomType.DiffusionDofBloom,
"Switching from Live to a plain adapter must not leak the Live auto-disable state.");
Debug.Log("[LiveDofFocusRegression] PASS: focus modes, authored enable, threshold equality/recovery, Live/helper camera isolation, user gate and paused restore.");
}
finally
{
UnityEngine.Object.DestroyImmediate(root);
UnityEngine.Object.DestroyImmediate(timelineData);
UnityEngine.Object.DestroyImmediate(worksheet);
typeof(Director).GetField("_instance", BindingFlags.Static | BindingFlags.NonPublic).SetValue(null, null);
typeof(PostImageEffectFeature).GetField("_runtimeParameter", BindingFlags.Static | BindingFlags.NonPublic)
.SetValue(null, previousRuntime);
+6 -3
View File
@@ -1,4 +1,4 @@
#if UNITY_EDITOR
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -208,8 +208,11 @@ public static class LiveRenderCapture
var live = main.Lives.FirstOrDefault(x => x.MusicId == plan.songId);
if (live == null || main.Characters.Count < live.MemberCount) return;
var selections = new List<LiveCharacterSelect>();
if (live.MemberCount != plan.characters.Length || live.BackGroundId != plan.stageId)
throw new InvalidOperationException("Reference song/stage/member count differs from loaded Live metadata.");
// Reference identity includes optional actors created by the native
// channel expansion; only MemberCount identities are selected in UI.
// The complete instantiated cast is still checked below.
if (live.MemberCount <= 0 || live.MemberCount > plan.characters.Length || live.BackGroundId != plan.stageId)
throw new InvalidOperationException("Reference song/stage/selected members differ from loaded Live metadata.");
for (int i = 0; i < live.MemberCount; ++i)
{
var item = new GameObject("CaptureSelection_" + i).AddComponent<LiveCharacterSelect>();
+44
View File
@@ -26,10 +26,54 @@ public static class LiveRenderSetup
renderer.SetDirty();
EditorUtility.SetDirty(feature);
EditorUtility.SetDirty(renderer);
InstallMirrorRenderer(renderer);
AssetDatabase.SaveAssets();
Debug.Log("[LiveRenderSetup] Installed recovered post effects: " + path);
}
private static void InstallMirrorRenderer(UniversalRendererData source)
{
const string path = "Assets/Resources/RenderPipeline/UMASimpleMirrorRenderer.asset";
var pipeline = AssetDatabase.LoadAssetAtPath<UniversalRenderPipelineAsset>(
"Assets/Resources/RenderPipeline/UMAUniversalRenderPipelineAsset.asset");
if (pipeline == null) throw new InvalidOperationException("Missing Live pipeline");
var simple = AssetDatabase.LoadAssetAtPath<UniversalRendererData>(path);
if (simple == null)
{
simple = UnityEngine.Object.Instantiate(source);
simple.name = "UMASimpleMirrorRenderer";
simple.rendererFeatures.Clear();
simple.opaqueLayerMask = 0;
simple.transparentLayerMask = 0;
AssetDatabase.CreateAsset(simple, path);
foreach (bool opaque in new[] { true, false })
{
var draw = ScriptableObject.CreateInstance<UnityEngine.Experimental.Rendering.Universal.RenderObjects>();
draw.name = opaque ? "SimpleMirrorOpaque" : "SimpleMirrorTransparent";
draw.settings.Event = opaque ? RenderPassEvent.BeforeRenderingOpaques : RenderPassEvent.BeforeRenderingTransparents;
draw.settings.filterSettings.LayerMask = -1;
draw.settings.filterSettings.RenderQueueType = opaque
? UnityEngine.Experimental.Rendering.Universal.RenderQueueType.Opaque
: UnityEngine.Experimental.Rendering.Universal.RenderQueueType.Transparent;
draw.settings.filterSettings.PassNames = new[] { "SimpleMirrorCaster" };
AssetDatabase.AddObjectToAsset(draw, simple);
simple.rendererFeatures.Add(draw);
EditorUtility.SetDirty(draw);
}
simple.SetDirty();
EditorUtility.SetDirty(simple);
}
var serialized = new SerializedObject(pipeline);
var renderers = serialized.FindProperty("m_RendererDataList");
if (renderers.arraySize > 1 && renderers.GetArrayElementAtIndex(1).objectReferenceValue != null &&
renderers.GetArrayElementAtIndex(1).objectReferenceValue != simple)
throw new InvalidOperationException("Renderer slot 1 is already owned by another renderer");
if (renderers.arraySize < 2) renderers.arraySize = 2;
renderers.GetArrayElementAtIndex(1).objectReferenceValue = simple;
serialized.ApplyModifiedPropertiesWithoutUndo();
EditorUtility.SetDirty(pipeline);
}
// Batch-mode contract checks. These validate state routing, not rendered pixels.
public static void Validate()
{
@@ -0,0 +1,157 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &-2427507773835696840
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 6b3d386ba5cd94485973aee1479b272e, type: 3}
m_Name: SimpleMirrorTransparent
m_EditorClassIdentifier:
m_Active: 1
settings:
passTag: RenderObjectsFeature
Event: 450
filterSettings:
RenderQueueType: 1
LayerMask:
serializedVersion: 2
m_Bits: 4294967295
PassNames:
- SimpleMirrorCaster
overrideMaterial: {fileID: 0}
overrideMaterialPassIndex: 0
overrideShader: {fileID: 0}
overrideShaderPassIndex: 0
overrideMode: 1
overrideDepthState: 0
depthCompareFunction: 4
enableWrite: 1
stencilSettings:
overrideStencilState: 0
stencilReference: 0
stencilCompareFunction: 8
passOperation: 0
failOperation: 0
zFailOperation: 0
cameraSettings:
overrideCamera: 0
restoreCamera: 1
offset: {x: 0, y: 0, z: 0, w: 0}
cameraFieldOfView: 60
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: de640fe3d0db1804a85f9fc8f5cadab6, type: 3}
m_Name: UMASimpleMirrorRenderer
m_EditorClassIdentifier:
debugShaders:
debugReplacementPS: {fileID: 4800000, guid: cf852408f2e174538bcd9b7fda1c5ae7,
type: 3}
hdrDebugViewPS: {fileID: 4800000, guid: 573620ae32aec764abd4d728906d2587, type: 3}
m_RendererFeatures:
- {fileID: 2511524374758812546}
- {fileID: -2427507773835696840}
m_RendererFeatureMap: a2e53b18a90641ffaee5ec1f99bbce1c
m_UseNativeRenderPass: 0
postProcessData: {fileID: 11400000, guid: 41439944d30ece34e96484bdb6645b55, type: 2}
xrSystemData: {fileID: 11400000, guid: 60e1133243b97e347b653163a8c01b64, type: 2}
shaders:
blitPS: {fileID: 4800000, guid: c17132b1f77d20942aa75f8429c0f8bc, type: 3}
copyDepthPS: {fileID: 4800000, guid: d6dae50ee9e1bfa4db75f19f99355220, type: 3}
screenSpaceShadowPS: {fileID: 4800000, guid: 0f854b35a0cf61a429bd5dcfea30eddd,
type: 3}
samplingPS: {fileID: 4800000, guid: 04c410c9937594faa893a11dceb85f7e, type: 3}
stencilDeferredPS: {fileID: 4800000, guid: e9155b26e1bc55942a41e518703fe304, type: 3}
fallbackErrorPS: {fileID: 4800000, guid: e6e9a19c3678ded42a3bc431ebef7dbd, type: 3}
fallbackLoadingPS: {fileID: 4800000, guid: 7f888aff2ac86494babad1c2c5daeee2, type: 3}
materialErrorPS: {fileID: 4800000, guid: 5fd9a8feb75a4b5894c241777f519d4e, type: 3}
coreBlitPS: {fileID: 4800000, guid: 93446b5c5339d4f00b85c159e1159b7c, type: 3}
coreBlitColorAndDepthPS: {fileID: 4800000, guid: d104b2fc1ca6445babb8e90b0758136b,
type: 3}
blitHDROverlay: {fileID: 4800000, guid: a89bee29cffa951418fc1e2da94d1959, type: 3}
cameraMotionVector: {fileID: 4800000, guid: c56b7e0d4c7cb484e959caeeedae9bbf,
type: 3}
objectMotionVector: {fileID: 4800000, guid: 7b3ede40266cd49a395def176e1bc486,
type: 3}
dataDrivenLensFlare: {fileID: 4800000, guid: 6cda457ac28612740adb23da5d39ea92,
type: 3}
terrainDetailLitPS: {fileID: 4800000, guid: f6783ab646d374f94b199774402a5144,
type: 3}
terrainDetailGrassPS: {fileID: 4800000, guid: e507fdfead5ca47e8b9a768b51c291a1,
type: 3}
terrainDetailGrassBillboardPS: {fileID: 4800000, guid: 29868e73b638e48ca99a19ea58c48d90,
type: 3}
m_AssetVersion: 2
m_OpaqueLayerMask:
serializedVersion: 2
m_Bits: 0
m_TransparentLayerMask:
serializedVersion: 2
m_Bits: 0
m_DefaultStencilState:
overrideStencilState: 0
stencilReference: 0
stencilCompareFunction: 8
passOperation: 2
failOperation: 0
zFailOperation: 0
m_ShadowTransparentReceive: 1
m_RenderingMode: 0
m_DepthPrimingMode: 0
m_CopyDepthMode: 0
m_AccurateGbufferNormals: 0
m_IntermediateTextureMode: 1
--- !u!114 &2511524374758812546
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 6b3d386ba5cd94485973aee1479b272e, type: 3}
m_Name: SimpleMirrorOpaque
m_EditorClassIdentifier:
m_Active: 1
settings:
passTag: RenderObjectsFeature
Event: 250
filterSettings:
RenderQueueType: 0
LayerMask:
serializedVersion: 2
m_Bits: 4294967295
PassNames:
- SimpleMirrorCaster
overrideMaterial: {fileID: 0}
overrideMaterialPassIndex: 0
overrideShader: {fileID: 0}
overrideShaderPassIndex: 0
overrideMode: 1
overrideDepthState: 0
depthCompareFunction: 4
enableWrite: 1
stencilSettings:
overrideStencilState: 0
stencilReference: 0
stencilCompareFunction: 8
passOperation: 0
failOperation: 0
zFailOperation: 0
cameraSettings:
overrideCamera: 0
restoreCamera: 1
offset: {x: 0, y: 0, z: 0, w: 0}
cameraFieldOfView: 60
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 9e7a4aa0d4373cf4c8147b114d770906
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:
@@ -18,6 +18,7 @@ MonoBehaviour:
m_RendererData: {fileID: 0}
m_RendererDataList:
- {fileID: 11400000, guid: 4f8c5d0b81b4504419b0d6335567efde, type: 2}
- {fileID: 11400000, guid: 9e7a4aa0d4373cf4c8147b114d770906, type: 2}
m_DefaultRendererIndex: 0
m_RequireDepthTexture: 1
m_RequireOpaqueTexture: 1
+3 -9
View File
@@ -1,4 +1,4 @@
using NAudio.Wave;
using NAudio.Wave;
using System;
using UnityEngine;
using System.IO;
@@ -9,19 +9,13 @@ namespace UmaMusumeAudio
{
public class UmaWaveStream : WaveStream
{
/*
* Open Umamusume > umamusume_Data > resources.assets with a hex editor.
* Check the results when finding the string "StreamingAssets".
* The key should be near a string named "cri_auth".
*/
private const ulong umaMusumeKey = 75923756697503;
private readonly HcaWaveStream hcaWaveStream;
public UmaWaveStream(AwbReader awbReader, int waveId)
{
ulong audioKey = Config.Instance.GetAudioKey();
Stream awbSubfile = awbReader.GetWaveSubfileStream(awbReader.Waves.Find((wave) => wave.WaveId == waveId));
hcaWaveStream = new HcaWaveStream(awbSubfile, MixKey(umaMusumeKey, awbReader.Subkey));
hcaWaveStream = new HcaWaveStream(awbSubfile, MixKey(audioKey, awbReader.Subkey));
}
public override WaveFormat WaveFormat => hcaWaveStream.WaveFormat;
+28 -2
View File
@@ -23,6 +23,9 @@ public class Config
public string ABKeyTip = "Key to read asset bundles";
public string ABKeyText;
public string AudioKeyTip = "Hexadecimal key to read game audio files (up to 16 hex digits, without 0x prefix)";
public string AudioKeyText = "";
public string LanguageTip = "Affects Uma names on the list. Language options: 0 - En, 1 - Jp, 2 - Simplified Chinese";
public Language Language = Language.En;
@@ -53,9 +56,15 @@ public class Config
public string AntiAliasingTip = "Display, screenshot antialiasing level. 0 - no AA, 1 - 2x MSAA, 2 - 4x MSAA, 3 - 8x MSAA";
public int AntiAliasing = 2;
public string TargetFrameRateTip = "Limits application frame rate. Available values: 60, 30";
public string TargetFrameRateTip = "Application frame rate: positive integer FPS, 0 = unlimited (desktop).";
public int TargetFrameRate = 60;
public int RenderScalePercent = 100;
public int AnisotropicFiltering = 2;
public int TextureMipmapLimit = 0;
public float LodBias = 2f;
public float ShadowDistance = 50f;
public bool RegionDetectionPassed = false;
public string VmdMorphConvertSettingTip = "The mapping of MMD mprphs to UMA mprphs during VMD recording, multiple UMA expression weights will be combined (not exceeding 1)";
@@ -223,9 +232,26 @@ public class Config
}
}
public ulong GetAudioKey()
{
if (string.IsNullOrWhiteSpace(AudioKeyText))
{
throw new InvalidOperationException("AudioKeyText is missing. Supply your authorized audio key in Config.json and restart the application.");
}
string keyText = AudioKeyText.Trim();
if (keyText.Length > 16 || !ulong.TryParse(keyText, System.Globalization.NumberStyles.AllowHexSpecifier,
System.Globalization.CultureInfo.InvariantCulture, out ulong key) || key == 0)
{
throw new InvalidOperationException("AudioKeyText must be a nonzero hexadecimal key of at most 16 digits, without a 0x prefix.");
}
return key;
}
public int GetTargetFrameRate()
{
return TargetFrameRate == 30 ? 30 : 60;
return TargetFrameRate <= 0 ? -1 : TargetFrameRate;
}
public bool TryGetNetworkProxyUri(out Uri proxyUri, out string error)
+166
View File
@@ -0,0 +1,166 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using UnityEngine;
public static class LiveAutoSelection
{
private sealed class Candidate
{
public CharaEntry Character;
public string CostumeId;
public Sprite Icon;
public int BodyTypeSub;
}
// Existing character, body costume and head costume choices are never replaced.
public static bool FillMissing(UmaViewerMain main, LiveEntry live,
IList<LiveCharacterSelect> slots, Sprite fallbackIcon = null)
{
if (main == null || live == null || slots == null) return false;
bool needsDefaults = false;
var used = new HashSet<int>();
foreach (var slot in slots)
{
if (slot == null) continue;
if (slot.CharaEntry != null && slot.CharaEntry.Id > 0) used.Add(slot.CharaEntry.Id);
if (slot.CharaEntry == null || slot.CharaEntry.Id <= 0 || string.IsNullOrEmpty(slot.CostumeId)) needsDefaults = true;
}
if (!needsDefaults) return true;
var defaults = GetWinningCostumes(main, fallbackIcon);
var singerIds = GetSingerIds(main, live.MusicId);
var singers = new List<Candidate>();
var others = new List<Candidate>();
foreach (var character in main.Characters)
{
if (character == null || character.IsMob || !defaults.TryGetValue(character.Id, out var candidate)) continue;
candidate.Character = character;
(singerIds.Contains(character.Id) ? singers : others).Add(candidate);
}
Shuffle(singers);
Shuffle(others);
foreach (var slot in slots)
{
if (slot == null) continue;
bool missingCharacter = slot.CharaEntry == null || slot.CharaEntry.Id <= 0;
bool missingCostume = string.IsNullOrEmpty(slot.CostumeId);
if (!missingCharacter && !missingCostume) continue;
Candidate selected;
if (missingCharacter)
{
selected = FindCandidate(main, singers, used, slot.CostumeId, true)
?? FindCandidate(main, others, used, slot.CostumeId, true)
?? FindCandidate(main, singers, used, slot.CostumeId, false)
?? FindCandidate(main, others, used, slot.CostumeId, false);
}
else
{
defaults.TryGetValue(slot.CharaEntry.Id, out selected);
if (slot.CharaEntry.IsMob) selected = null;
}
if (selected == null) return false;
if (missingCharacter) slot.CharaEntry = selected.Character;
if (missingCostume) slot.CostumeId = selected.CostumeId;
used.Add(slot.CharaEntry.Id);
if (slot.CharaImage != null)
{
slot.CharaImage.enabled = true;
slot.CharaImage.sprite = slot.CharaEntry.Icon;
}
if (missingCostume && slot.CostumeImage != null)
slot.CostumeImage.sprite = selected.Icon;
}
return true;
}
private static Dictionary<int, Candidate> GetWinningCostumes(UmaViewerMain main, Sprite fallbackIcon)
{
var result = new Dictionary<int, Candidate>();
var rows = UmaDatabaseController.Instance.DressData;
if (rows == null) return result;
foreach (DataRow row in rows)
{
if (Convert.ToInt32(row["costume_type"]) != 1) continue;
int characterId = Convert.ToInt32(row["chara_id"]);
int subtype = Convert.ToInt32(row["body_type_sub"]);
string costumeId = subtype.ToString("D2", CultureInfo.InvariantCulture);
string body = UmaDatabaseController.BodyPath + $"bdy{characterId}_{costumeId}/pfb_bdy{characterId}_{costumeId}";
if (characterId <= 0 || !main.AbList.TryGetValue(body, out var entry) || entry == null) continue;
if (result.TryGetValue(characterId, out var previous) && previous.BodyTypeSub <= subtype) continue;
Sprite icon = fallbackIcon;
foreach (var costume in main.Costumes)
{
if (costume.CharaId != characterId || costume.BodyTypeSub != subtype) continue;
if (costume.Icon != null) icon = costume.Icon;
break;
}
result[characterId] = new Candidate { CostumeId = costumeId, Icon = icon, BodyTypeSub = subtype };
}
return result;
}
private static HashSet<int> GetSingerIds(UmaViewerMain main, int musicId)
{
string song = musicId.ToString("D4", CultureInfo.InvariantCulture);
string prefix = $"sound/l/{song}/snd_bgm_live_{song}_chara_";
var result = new HashSet<int>();
foreach (var sound in main.AbSounds)
{
string name = sound.Name;
if (!name.StartsWith(prefix, StringComparison.Ordinal) || !name.EndsWith("awb", StringComparison.OrdinalIgnoreCase)) continue;
int separator = name.IndexOf('_', prefix.Length);
if (separator < 0 || !name.Substring(separator).StartsWith("_01", StringComparison.Ordinal)) continue;
if (int.TryParse(name.Substring(prefix.Length, separator - prefix.Length), out int characterId))
result.Add(characterId);
}
return result;
}
private static Candidate FindCandidate(UmaViewerMain main, List<Candidate> candidates,
HashSet<int> used, string costumeId, bool distinct)
{
if (candidates.Count == 0) return null;
int start = distinct ? 0 : UnityEngine.Random.Range(0, candidates.Count);
for (int i = 0; i < candidates.Count; i++)
{
var candidate = candidates[(start + i) % candidates.Count];
if (distinct && used.Contains(candidate.Character.Id)) continue;
if (string.IsNullOrEmpty(costumeId) || HasBody(main, candidate.Character, costumeId)) return candidate;
}
return null;
}
private static bool HasBody(UmaViewerMain main, CharaEntry character, string costumeId)
{
if (costumeId.Length < 4)
return main.AbList.ContainsKey(UmaDatabaseController.BodyPath + $"bdy{character.Id}_{costumeId}/pfb_bdy{character.Id}_{costumeId}");
int separator = costumeId.LastIndexOf('_');
if (separator < 0) return false;
var rows = UmaDatabaseController.Instance.CharaData;
if (rows == null) return false;
foreach (var row in rows)
{
if (Convert.ToInt32(row["id"]) != character.Id) continue;
string shortId = costumeId.Substring(0, separator);
string body = UmaDatabaseController.BodyPath + $"bdy{shortId}/pfb_bdy{costumeId}_{row["height"]}_{row["shape"]}_{row["bust"]}";
return main.AbList.ContainsKey(body);
}
return false;
}
private static void Shuffle(List<Candidate> candidates)
{
for (int i = candidates.Count - 1; i > 0; i--)
{
int other = UnityEngine.Random.Range(0, i + 1);
var candidate = candidates[i];
candidates[i] = candidates[other];
candidates[other] = candidate;
}
}
}
+11
View File
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e208e92f2051441da44fe056b39ee550
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+6 -36
View File
@@ -1,4 +1,4 @@
using System.Collections;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
@@ -23,7 +23,6 @@ public class LiveViewerUI : MonoBehaviour
public List<UmaLyricsData> CurrentLyrics = new List<UmaLyricsData>();
private UnityEngine.UI.Text progressSeconds;
private UnityEngine.UI.Text dofButtonLabel;
private int displayedCurrentTenth = -1;
private int displayedTotalTenth = -1;
@@ -36,6 +35,8 @@ public class LiveViewerUI : MonoBehaviour
new Config();
}
ApplyFrameRateOptions();
UISettingsGraphics.Build(FrameRateDropDown);
RuntimeGraphicsSettings.Apply();
UmaViewerMain.ApplyFrameRateLimit();
height = BottonUITransform.rect.height;
@@ -59,32 +60,6 @@ public class LiveViewerUI : MonoBehaviour
progressSeconds.alignment = TextAnchor.MiddleRight;
progressSeconds.text = "0.0s / 0.0s";
var buttonObject = new GameObject("DofDiagnosticToggle", typeof(RectTransform),
typeof(UnityEngine.UI.Image), typeof(UnityEngine.UI.Button));
buttonObject.layer = BottonUITransform.gameObject.layer;
var buttonRect = (RectTransform)buttonObject.transform;
buttonRect.SetParent(BottonUITransform, false);
buttonRect.anchorMin = buttonRect.anchorMax = new Vector2(0, 0.5f);
buttonRect.pivot = new Vector2(0, 0.5f);
buttonRect.anchoredPosition = new Vector2(8, 0);
buttonRect.sizeDelta = new Vector2(176, 24);
var image = buttonObject.GetComponent<UnityEngine.UI.Image>();
image.color = new Color(0.08f, 0.08f, 0.08f, 0.9f);
var button = buttonObject.GetComponent<UnityEngine.UI.Button>();
button.targetGraphic = image;
button.navigation = new UnityEngine.UI.Navigation { mode = UnityEngine.UI.Navigation.Mode.None };
button.onClick.AddListener(() =>
{
Gallop.GallopImageEffect.SetUserDofEnabled(!Gallop.GallopImageEffect.UserDofEnabled);
RefreshDofLabel();
OnMouse(true);
OnMouse(false);
});
dofButtonLabel = CreateDiagnosticText("Label", buttonRect);
dofButtonLabel.rectTransform.anchorMin = Vector2.zero;
dofButtonLabel.rectTransform.anchorMax = Vector2.one;
dofButtonLabel.rectTransform.sizeDelta = Vector2.zero;
RefreshDofLabel();
}
private UnityEngine.UI.Text CreateDiagnosticText(string name, RectTransform parent)
@@ -106,11 +81,6 @@ public class LiveViewerUI : MonoBehaviour
return text;
}
private void RefreshDofLabel()
{
if (dofButtonLabel != null)
dofButtonLabel.text = Gallop.GallopImageEffect.UserDofEnabled ? "DOF: ON (test)" : "DOF: OFF";
}
private void LateUpdate()
{
@@ -157,7 +127,7 @@ public class LiveViewerUI : MonoBehaviour
public void SetFrameRate(int fps)
{
Config.Instance.TargetFrameRate = fps == 1 ? 30 : 60;
Config.Instance.TargetFrameRate = UISettingsGraphics.FrameRateAt(fps);
Config.Instance.UpdateConfig(false);
UmaViewerMain.ApplyFrameRateLimit();
}
@@ -167,8 +137,8 @@ public class LiveViewerUI : MonoBehaviour
if (FrameRateDropDown == null) return;
FrameRateDropDown.ClearOptions();
FrameRateDropDown.AddOptions(new List<string> { "60", "30" });
FrameRateDropDown.SetValueWithoutNotify(Config.Instance.GetTargetFrameRate() == 30 ? 1 : 0);
FrameRateDropDown.AddOptions(UISettingsGraphics.FrameRateLabels());
FrameRateDropDown.SetValueWithoutNotify(UISettingsGraphics.FrameRateIndex());
FrameRateDropDown.RefreshShownValue();
}
@@ -0,0 +1,42 @@
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
// Quality changes affect an in-memory copy, never the authored pipeline asset.
public static class RuntimeGraphicsSettings
{
private static UniversalRenderPipelineAsset source;
private static UniversalRenderPipelineAsset runtime;
private static readonly int[] Samples = { 1, 2, 4, 8 };
public static void Apply()
{
var config = Config.Instance;
if (config == null) return;
int samples = Samples[Mathf.Clamp(config.AntiAliasing, 0, 3)];
QualitySettings.antiAliasing = samples == 1 ? 0 : samples;
QualitySettings.anisotropicFiltering = (AnisotropicFiltering)Mathf.Clamp(config.AnisotropicFiltering, 0, 2);
QualitySettings.globalTextureMipmapLimit = Mathf.Clamp(config.TextureMipmapLimit, 0, 3);
QualitySettings.lodBias = Mathf.Clamp(config.LodBias, 0.3f, 2f);
var active = GraphicsSettings.currentRenderPipeline as UniversalRenderPipelineAsset;
if (active == null) return;
if (active != runtime)
{
if (active != source || runtime == null)
{
if (runtime != null) Object.Destroy(runtime);
source = active;
runtime = Object.Instantiate(active);
runtime.name = active.name + " (Runtime Graphics)";
runtime.hideFlags = HideFlags.DontSave;
}
// A quality-level override takes precedence over the default pipeline.
if (QualitySettings.renderPipeline != null) QualitySettings.renderPipeline = runtime;
else GraphicsSettings.renderPipelineAsset = runtime;
}
runtime.msaaSampleCount = samples;
runtime.renderScale = Mathf.Clamp(config.RenderScalePercent / 100f, 0.5f, 2f);
runtime.shadowDistance = Mathf.Clamp(config.ShadowDistance, 0f, 150f);
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a07c0541500d4eae8c5910a73925a6c3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+1 -3
View File
@@ -122,14 +122,12 @@ public class UISettingsCamera : MonoBehaviour
/// <summary> Converts values 1-4 to valid AA values </summary>
public void ChangeAntiAliasing(int value)
{
int[] aaValues = { 0, 2, 4, 8 };
QualitySettings.antiAliasing = aaValues[value];
if (Config.Instance.AntiAliasing != value)
{
Config.Instance.AntiAliasing = value;
Config.Instance.UpdateConfig(false);
}
RuntimeGraphicsSettings.Apply();
}
}
@@ -0,0 +1,217 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.UI;
public static class UISettingsGraphics
{
private static readonly int[] Rates = { 60, 30, 90, 120, 144, 165, 240, 0 };
public static List<string> FrameRateLabels()
{
var labels = new List<string>();
foreach (int rate in Rates) labels.Add(rate == 0 ? "Unlimited" : rate + " FPS");
if (FrameRateIndex() == Rates.Length) labels.Add(Config.Instance.TargetFrameRate + " FPS");
return labels;
}
public static int FrameRateIndex()
{
int rate = Math.Max(0, Config.Instance.TargetFrameRate);
int index = Array.IndexOf(Rates, rate);
return index < 0 ? Rates.Length : index;
}
public static int FrameRateAt(int index)
{
return index >= 0 && index < Rates.Length ? Rates[index] : Config.Instance.TargetFrameRate;
}
public static InputField AddFrameRateInput(Transform parent, Action refresh, Font font = null)
{
return AddNumber(parent, "Custom FPS (0 = unlimited)", Config.Instance.TargetFrameRate.ToString(), true,
text =>
{
if (!int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out int rate) || rate < 0)
return Config.Instance.TargetFrameRate.ToString();
Config.Instance.TargetFrameRate = rate;
Config.Instance.UpdateConfig(false);
UmaViewerMain.ApplyFrameRateLimit();
refresh();
return rate.ToString();
}, font);
}
public static void Build(Dropdown frameRate)
{
if (frameRate == null) return;
var template = (RectTransform)frameRate.transform.parent;
var parent = (RectTransform)template.parent;
if (parent.Find("GraphicsOptions") != null) return;
var window = parent.parent as RectTransform;
if (window != null) window.sizeDelta = new Vector2(340, 400);
var layout = parent.GetComponent<VerticalLayoutGroup>();
if (layout != null)
{
layout.childControlWidth = true;
layout.childForceExpandWidth = true;
}
var font = frameRate.captionText.font;
FitDropdown(template, frameRate, "Frame Rate");
// Keep the original camera/lyrics controls and put quality rows in their parent.
// Scrolling keeps all options reachable on smaller windows.
var scrollObject = new GameObject("GraphicsOptions", typeof(RectTransform), typeof(Image), typeof(ScrollRect), typeof(LayoutElement));
scrollObject.transform.SetParent(parent, false);
scrollObject.layer = parent.gameObject.layer;
var scrollRect = (RectTransform)scrollObject.transform;
scrollRect.sizeDelta = new Vector2(320, 280);
scrollObject.GetComponent<LayoutElement>().preferredHeight = 280;
scrollObject.GetComponent<Image>().color = new Color(0, 0, 0, 0.1f);
var viewport = new GameObject("Viewport", typeof(RectTransform), typeof(RectMask2D));
viewport.transform.SetParent(scrollRect, false);
Stretch((RectTransform)viewport.transform, 0, 1, 0, 0);
var contentObject = new GameObject("Content", typeof(RectTransform), typeof(VerticalLayoutGroup), typeof(ContentSizeFitter));
contentObject.transform.SetParent(viewport.transform, false);
var content = (RectTransform)contentObject.transform;
content.anchorMin = new Vector2(0, 1);
content.anchorMax = Vector2.one;
content.pivot = new Vector2(0.5f, 1);
content.sizeDelta = Vector2.zero;
var contentLayout = contentObject.GetComponent<VerticalLayoutGroup>();
contentLayout.spacing = 5;
contentLayout.childControlHeight = false;
contentLayout.childForceExpandHeight = false;
contentLayout.childControlWidth = true;
contentObject.GetComponent<ContentSizeFitter>().verticalFit = ContentSizeFitter.FitMode.PreferredSize;
var scroll = scrollObject.GetComponent<ScrollRect>();
scroll.viewport = (RectTransform)viewport.transform;
scroll.content = content;
scroll.horizontal = false;
scroll.movementType = ScrollRect.MovementType.Clamped;
scroll.scrollSensitivity = 30;
var customFps = AddFrameRateInput(content, () => RefreshFrameRate(frameRate), font);
frameRate.onValueChanged.AddListener(index => customFps.SetTextWithoutNotify(FrameRateAt(index).ToString()));
AddChoice(content, template, "MSAA", new[] { "Off", "2x", "4x", "8x" }, Config.Instance.AntiAliasing,
value => Config.Instance.AntiAliasing = value);
AddNumber(content, "Render Scale (%)", Config.Instance.RenderScalePercent.ToString(), true, text =>
{
if (int.TryParse(text, out int value) && value >= 50 && value <= 200)
Config.Instance.RenderScalePercent = value;
SaveGraphics();
return Config.Instance.RenderScalePercent.ToString();
}, font);
AddChoice(content, template, "Anisotropic Filter", new[] { "Off", "Per Texture", "Force On" }, Config.Instance.AnisotropicFiltering,
value => Config.Instance.AnisotropicFiltering = value);
AddChoice(content, template, "Texture Quality", new[] { "Full", "Half", "Quarter", "Eighth" }, Config.Instance.TextureMipmapLimit,
value => Config.Instance.TextureMipmapLimit = value);
AddNumber(content, "LOD Bias (0.3 - 2)", Config.Instance.LodBias.ToString(CultureInfo.InvariantCulture), false, text =>
{
if (float.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out float value) && value >= 0.3f && value <= 2f)
Config.Instance.LodBias = value;
SaveGraphics();
return Config.Instance.LodBias.ToString(CultureInfo.InvariantCulture);
}, font);
AddNumber(content, "Shadow Distance", Config.Instance.ShadowDistance.ToString(CultureInfo.InvariantCulture), false, text =>
{
if (float.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out float value) && value >= 0 && value <= 150)
Config.Instance.ShadowDistance = value;
SaveGraphics();
return Config.Instance.ShadowDistance.ToString(CultureInfo.InvariantCulture);
}, font);
}
private static void RefreshFrameRate(Dropdown dropdown)
{
dropdown.ClearOptions();
dropdown.AddOptions(FrameRateLabels());
dropdown.SetValueWithoutNotify(FrameRateIndex());
dropdown.RefreshShownValue();
}
private static void SaveGraphics()
{
Config.Instance.UpdateConfig(false);
RuntimeGraphicsSettings.Apply();
if (UmaViewerUI.Instance != null && UmaViewerUI.Instance.CameraSettings != null)
UmaViewerUI.Instance.CameraSettings.AAModeDropdown.SetValueWithoutNotify(Config.Instance.AntiAliasing);
}
private static void AddChoice(Transform parent, RectTransform template, string label, string[] options, int value, Action<int> change)
{
var row = UnityEngine.Object.Instantiate(template.gameObject, parent);
row.name = label;
var dropdown = row.GetComponentInChildren<Dropdown>();
dropdown.onValueChanged = new Dropdown.DropdownEvent();
dropdown.ClearOptions();
dropdown.AddOptions(new List<string>(options));
dropdown.SetValueWithoutNotify(Mathf.Clamp(value, 0, options.Length - 1));
dropdown.onValueChanged.AddListener(index => { change(index); SaveGraphics(); });
FitDropdown((RectTransform)row.transform, dropdown, label);
}
private static void FitDropdown(RectTransform row, Dropdown dropdown, string label)
{
row.sizeDelta = new Vector2(320, 30);
Stretch((RectTransform)dropdown.transform, 0.58f, 1, 0, 0);
foreach (var text in row.GetComponentsInChildren<Text>(true))
{
if (text.transform.IsChildOf(dropdown.transform)) continue;
text.text = label;
text.fontSize = 14;
text.alignment = TextAnchor.MiddleLeft;
Stretch(text.rectTransform, 0, 0.56f, 0, 0);
}
}
private static InputField AddNumber(Transform parent, string label, string value, bool integer, Func<string, string> submit, Font font)
{
var row = new GameObject(label, typeof(RectTransform), typeof(LayoutElement));
row.transform.SetParent(parent, false);
row.layer = parent.gameObject.layer;
((RectTransform)row.transform).sizeDelta = new Vector2(320, 30);
row.GetComponent<LayoutElement>().preferredHeight = 30;
var caption = AddText(row.transform, "Label", label, font);
Stretch(caption.rectTransform, 0, 0.58f, 0, 0);
var field = new GameObject("Input", typeof(RectTransform), typeof(Image), typeof(InputField));
field.transform.SetParent(row.transform, false);
field.layer = row.layer;
Stretch((RectTransform)field.transform, 0.6f, 1, 0, 0);
field.GetComponent<Image>().color = Color.white;
var text = AddText(field.transform, "Text", value, font);
text.color = Color.black;
Stretch(text.rectTransform, 0, 1, 6, -6);
var input = field.GetComponent<InputField>();
input.targetGraphic = field.GetComponent<Image>();
input.textComponent = text;
input.contentType = integer ? InputField.ContentType.IntegerNumber : InputField.ContentType.DecimalNumber;
input.text = value;
input.onEndEdit.AddListener(raw => input.SetTextWithoutNotify(submit(raw)));
return input;
}
private static Text AddText(Transform parent, string name, string value, Font font)
{
var go = new GameObject(name, typeof(RectTransform), typeof(Text));
go.transform.SetParent(parent, false);
go.layer = parent.gameObject.layer;
var text = go.GetComponent<Text>();
text.font = font != null ? font : Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
text.fontSize = 14;
text.color = Color.white;
text.alignment = TextAnchor.MiddleLeft;
text.raycastTarget = false;
text.text = value;
return text;
}
private static void Stretch(RectTransform rect, float left, float right, float insetLeft, float insetRight)
{
rect.anchorMin = new Vector2(left, 0);
rect.anchorMax = new Vector2(right, 1);
rect.offsetMin = new Vector2(insetLeft, 0);
rect.offsetMax = new Vector2(insetRight, 0);
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2ff4d9bec2d640c58a313788b1e66813
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+18 -14
View File
@@ -23,6 +23,7 @@ public class UISettingsOther : MonoBehaviour
public TMP_Dropdown LanguageDropdown;
public TMP_Dropdown FrameRateDropdown;
private GameObject _runtimeFrameRateRow;
private InputField _customFrameRateInput;
private IEnumerator _updateResVerCoroutine;
public void ApplySettings()
@@ -32,8 +33,8 @@ public class UISettingsOther : MonoBehaviour
WorkModeDropdown.SetValueWithoutNotify((int)Config.Instance.WorkMode);
RegionDropdown.SetValueWithoutNotify((int)Config.Instance.Region);
LanguageDropdown.SetValueWithoutNotify(LanguageToDropdownValue(Config.Instance.Language));
FrameRateDropdown?.SetValueWithoutNotify(FrameRateToDropdownValue(Config.Instance.GetTargetFrameRate()));
FrameRateDropdown?.RefreshShownValue();
if (FrameRateDropdown != null) RefreshFrameRateOptions();
if (_customFrameRateInput != null) _customFrameRateInput.SetTextWithoutNotify(Config.Instance.TargetFrameRate.ToString());
UmaViewerMain.ApplyFrameRateLimit();
UpdateDBButton.interactable = (Config.Instance.WorkMode == WorkMode.Standalone);
}
@@ -120,32 +121,27 @@ public class UISettingsOther : MonoBehaviour
FrameRateDropdown = _runtimeFrameRateRow.GetComponentInChildren<TMP_Dropdown>(true);
FrameRateDropdown.name = "FrameRateDropdown";
FrameRateDropdown.ClearOptions();
FrameRateDropdown.AddOptions(new List<string> { "60 FPS", "30 FPS" });
FrameRateDropdown.AddOptions(UISettingsGraphics.FrameRateLabels());
FrameRateDropdown.onValueChanged = new TMP_Dropdown.DropdownEvent();
FrameRateDropdown.onValueChanged.AddListener(ChangeFrameRate);
var customInput = UISettingsGraphics.AddFrameRateInput(parent, RefreshFrameRateOptions);
_customFrameRateInput = customInput;
FrameRateDropdown.onValueChanged.AddListener(index => customInput.SetTextWithoutNotify(UISettingsGraphics.FrameRateAt(index).ToString()));
customInput.transform.parent.SetSiblingIndex(_runtimeFrameRateRow.transform.GetSiblingIndex() + 1);
var parentRect = parent as RectTransform;
var sourceRect = sourceRow as RectTransform;
if (parentRect != null && sourceRect != null)
{
parentRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, parentRect.rect.height + sourceRect.rect.height);
parentRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, parentRect.rect.height + sourceRect.rect.height + 30);
LayoutRebuilder.MarkLayoutForRebuild(parentRect);
}
}
private int FrameRateToDropdownValue(int frameRate)
{
return frameRate == 30 ? 1 : 0;
}
private int DropdownValueToFrameRate(int value)
{
return value == 1 ? 30 : 60;
}
public void ChangeFrameRate(int value)
{
var frameRate = DropdownValueToFrameRate(value);
var frameRate = UISettingsGraphics.FrameRateAt(value);
if (Config.Instance.TargetFrameRate != frameRate)
{
Config.Instance.TargetFrameRate = frameRate;
@@ -154,6 +150,14 @@ public class UISettingsOther : MonoBehaviour
UmaViewerMain.ApplyFrameRateLimit();
}
private void RefreshFrameRateOptions()
{
FrameRateDropdown.ClearOptions();
FrameRateDropdown.AddOptions(UISettingsGraphics.FrameRateLabels());
FrameRateDropdown.SetValueWithoutNotify(UISettingsGraphics.FrameRateIndex());
FrameRateDropdown.RefreshShownValue();
}
public void ChangeLanguage(int lang)
{
Language language = DropdownValueToLanguage(lang);
+120
View File
@@ -88,6 +88,110 @@ public class UmaContainerCharacter : UmaContainer
private Material[] _faceMaterials;
private bool _faceLightInitialized;
private readonly HashSet<Renderer> _mirrorHeadRenderers = new HashSet<Renderer>();
private GameObject[] _mirrorAllRendererObjects = Array.Empty<GameObject>();
private GameObject[] _mirrorBodyRendererObjects = Array.Empty<GameObject>();
private GameObject[] _mirrorChangedObjects = Array.Empty<GameObject>();
private int[] _mirrorOriginalLayers = Array.Empty<int>();
private int _mirrorChangedCount;
private bool _mirrorLayerCacheDirty = true;
private bool _mirrorLayerCacheReady;
private void RegisterMirrorHeadRenderers(GameObject source)
{
RestoreMirrorChangedLayers();
if (source != null)
{
var renderers = source.GetComponentsInChildren<Renderer>(true);
for (int i = 0; i < renderers.Length; i++)
_mirrorHeadRenderers.Add(renderers[i]);
}
InvalidateMirrorLayerCache();
}
private void InvalidateMirrorLayerCache()
{
RestoreMirrorChangedLayers();
_mirrorLayerCacheDirty = true;
if (_mirrorLayerCacheReady)
PrepareMirrorLayerCache();
}
internal void PrepareMirrorLayerCache()
{
if (!_mirrorLayerCacheDirty)
return;
RestoreMirrorChangedLayers();
var renderers = GetComponentsInChildren<Renderer>(true);
var all = new List<GameObject>(renderers.Length);
var body = new List<GameObject>(renderers.Length);
var seen = new HashSet<GameObject>();
var headObjects = new HashSet<GameObject>();
for (int i = 0; i < renderers.Length; i++)
if (renderers[i] != null && _mirrorHeadRenderers.Contains(renderers[i]))
headObjects.Add(renderers[i].gameObject);
for (int i = 0; i < renderers.Length; i++)
{
var renderer = renderers[i];
if (renderer == null || !seen.Add(renderer.gameObject))
continue;
all.Add(renderer.gameObject);
if (!headObjects.Contains(renderer.gameObject))
body.Add(renderer.gameObject);
}
_mirrorAllRendererObjects = all.ToArray();
_mirrorBodyRendererObjects = body.ToArray();
if (_mirrorChangedObjects.Length < all.Count)
{
_mirrorChangedObjects = new GameObject[all.Count];
_mirrorOriginalLayers = new int[all.Count];
}
_mirrorLayerCacheDirty = false;
_mirrorLayerCacheReady = true;
}
internal void SetLayerBeforeMirrorCameraRendering(bool bodyBit, bool headBit, int layer)
{
if (!bodyBit || layer < 0)
return;
RestoreMirrorChangedLayers();
var objects = headBit ? _mirrorAllRendererObjects : _mirrorBodyRendererObjects;
for (int i = 0; i < objects.Length; i++)
{
var obj = objects[i];
if (obj == null)
continue;
_mirrorChangedObjects[_mirrorChangedCount] = obj;
_mirrorOriginalLayers[_mirrorChangedCount] = obj.layer;
_mirrorChangedCount++;
obj.layer = layer;
}
}
internal void RestoreMirrorChangedLayers()
{
while (_mirrorChangedCount > 0)
{
int index = --_mirrorChangedCount;
var obj = _mirrorChangedObjects[index];
_mirrorChangedObjects[index] = null;
if (obj != null)
obj.layer = _mirrorOriginalLayers[index];
}
}
private void OnDisable()
{
RestoreMirrorChangedLayers();
}
private void OnDestroy()
{
RestoreMirrorChangedLayers();
}
private static readonly int ID_FaceCenterPos = Shader.PropertyToID("_FaceCenterPos");
private static readonly int ID_FaceUp = Shader.PropertyToID("_FaceUp");
private static readonly int ID_FaceForward = Shader.PropertyToID("_FaceForward");
@@ -184,6 +288,10 @@ public class UmaContainerCharacter : UmaContainer
public void MergeModel()
{
if (!Body) return;
RestoreMirrorChangedLayers();
// Capture source identity before MergeModel reparents Head/Hair children.
RegisterMirrorHeadRenderers(Head);
RegisterMirrorHeadRenderers(Hair);
var bodySkinnedMeshRenderer = Body.GetComponentInChildren<SkinnedMeshRenderer>();
var bodyBones = bodySkinnedMeshRenderer.bones.ToDictionary(bone => bone.name, bone => bone.transform);
List<Transform> emptyBones = new List<Transform>();
@@ -300,12 +408,16 @@ public class UmaContainerCharacter : UmaContainer
}
}
}
InvalidateMirrorLayerCache();
PrepareMirrorLayerCache();
}
public void MergeHairModel()
{
if (!Head || !Hair) return;
RestoreMirrorChangedLayers();
RegisterMirrorHeadRenderers(Hair);
var bodyBones = Head.GetComponentInChildren<SkinnedMeshRenderer>().bones.ToDictionary(bone => bone.name, bone => bone.transform);
List<Transform> emptyBones = new List<Transform>();
@@ -326,6 +438,7 @@ public class UmaContainerCharacter : UmaContainer
Hair.gameObject.SetActive(false);
emptyBones.ForEach(a => { if (a) Destroy(a.gameObject); });
InvalidateMirrorLayerCache();
}
public void SetHeight(int scale = 0)
@@ -1048,6 +1161,7 @@ public class UmaContainerCharacter : UmaContainer
BodyShaderEffectData.Initialize();
}
}
InvalidateMirrorLayerCache();
}
public void LoadHead(UmaDatabaseEntry entry)
@@ -1055,6 +1169,7 @@ public class UmaContainerCharacter : UmaContainer
var textures = MobHeadTextures;
GameObject head = InstantiateEntry(entry, transform);
Head = head;
RegisterMirrorHeadRenderers(head);
AssetTable table = null;
if (!IsMini)
@@ -1229,6 +1344,7 @@ public class UmaContainerCharacter : UmaContainer
{
GameObject hair = InstantiateEntry(entry, transform);
Hair = hair;
RegisterMirrorHeadRenderers(hair);
var textures = MobHeadTextures;
foreach (Renderer r in hair.GetComponentsInChildren<Renderer>())
{
@@ -1282,6 +1398,7 @@ public class UmaContainerCharacter : UmaContainer
{
GameObject go = entry.Get<GameObject>();
Tail = Instantiate(go, transform);
InvalidateMirrorLayerCache();
}
@@ -1305,6 +1422,7 @@ public class UmaContainerCharacter : UmaContainer
}
}
}
InvalidateMirrorLayerCache();
}
public void LoadTear(UmaDatabaseEntry entry)
@@ -1897,6 +2015,8 @@ public class UmaContainerCharacter : UmaContainer
emotionDriven.FaceDrivenKeyTarget = faceDriven;
emotionDriven.FaceEmotionKey = UmaDatabaseController.Instance.FaceTypeData;
emotionDriven.Initialize();
// Facial attachments are explicit head renderers, including inactive manga/tears.
RegisterMirrorHeadRenderers(headBone);
}
public void SetupBoneHandles()
+25 -28
View File
@@ -1,4 +1,4 @@
using System.Collections.Generic;
using System.Collections.Generic;
using UnityEngine;
using Gallop;
using System;
@@ -111,39 +111,36 @@ public class PartEntry
public int SingerCount = 0;
public PartEntry(string data)
{
string[] lines = data.Split('\n');
string[] names = lines[0].Split(',');
foreach (var name in names)
var lines = data.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
var names = lines[0].Split(',');
var columns = new Dictionary<string, int>(StringComparer.Ordinal);
for (int j = 0; j < names.Length; j++)
{
var temp = name;
temp.Replace("lleft", "left2");
temp.Replace("rright", "right2");
temp.Replace("llleft", "left3");
temp.Replace("rrright", "right3");
PartSettings[temp] = new List<float>();
string name = names[j].Trim();
int suffix = name.IndexOf('_');
string part = suffix < 0 ? name : name.Substring(0, suffix);
switch (part)
{
case "lleft": part = "left2"; break;
case "rright": part = "right2"; break;
case "llleft": part = "left3"; break;
case "rrright": part = "right3"; break;
}
name = part + (suffix < 0 ? "" : name.Substring(suffix));
columns[name] = j;
PartSettings[name] = new List<float>();
}
for (int i = 1; i < lines.Length - 1; i++)
for (int i = 1; i < lines.Length; i++)
{
var values = lines[i].Split(',');
for (int j = 0; j < names.Length; j++)
{
PartSettings[names[j]].Add((float)Convert.ToDouble(values[j]));
}
foreach (var column in columns)
PartSettings[column.Key].Add(float.Parse(values[column.Value], System.Globalization.CultureInfo.InvariantCulture));
}
foreach(var part in PartSettings)
foreach (var part in PartSettings)
{
if (part.Key != "time" && !part.Key.Contains("_"))
{
if (part.Value.FindAll(v => v > 0).Count > 0)
{
SingerCount += 1;
}
}
}
if (part.Key != "time" && !part.Key.Contains("_") && part.Value.Exists(v => v > 0f))
SingerCount++;
}
}
}
+57 -99
View File
@@ -29,6 +29,7 @@ public class UmaViewerAudio
{
if (cur_active_source == index && !forceUpdate) return;
cur_active_source = index;
activeSource = null;
for(int i = 0; i < sourceList.Count; i++)
{
if (i + 1 == index)
@@ -46,16 +47,14 @@ public class UmaViewerAudio
public void SetVolume(float volume)
{
if (volume == this.volume || !activeSource) return;
this.volume = volume;
activeSource.volume = volume;
if (activeSource) activeSource.volume = volume;
}
public void SetPanStereo(float pan)
{
if (pan == this.pan || !activeSource) return;
this.pan = pan;
activeSource.panStereo = pan;
if (activeSource) activeSource.panStereo = pan;
}
}
@@ -132,111 +131,70 @@ public class UmaViewerAudio
right3 = 6,
}
// Original .cctor 0x1b8ea00, GetVolume 0x1b8d670 and GetPartData 0x1b8d290.
static readonly float[] DefaultVolumes = { 0f, .79f, .89f, 1f, 1.12f, 1.26f };
static readonly float[] DefaultVolumeRates = { 0f, .79f, .79f, .56f, .53f, .47f, .42f, .37f };
static readonly int[][] DefaultVolumeIndices = {
new[] { 0 }, new[] { 5 }, new[] { 2, 2 }, new[] { 3, 5, 3 },
new[] { 3, 3, 3, 3 }, new[] { 1, 2, 4, 2, 1 },
new[] { 3, 3, 3, 3, 3, 3 }, new[] { 1, 1, 2, 4, 2, 1, 1 }
};
static readonly float[][] DefaultPans = {
new[] { 0f }, new[] { 0f }, new[] { -.15f, .15f }, new[] { -.3f, 0f, .3f },
new[] { -.3f, -.1f, .1f, .3f }, new[] { -.3f, -.15f, 0f, .15f, .3f },
new[] { -.3f, -.2f, -.1f, .1f, .2f, .3f }, new[] { -.3f, -.2f, -.1f, 0f, .1f, .2f, .3f }
};
static readonly string[] OrderedParts = { "left3", "left2", "left", "center", "right", "right2", "right3" };
static public void AlterUpdate(float _liveCurrentTime, PartEntry partInfo, List<CuteAudioSource> liveVocal, bool forceUpdate = false)
{
var timeLineData = partInfo.PartSettings["time"];
var targetIndex = 0;
for (int i = timeLineData.Count - 1; i >= 0; i--)
{
if (_liveCurrentTime >= (double)timeLineData[i] / 1000)
{
targetIndex = i;
break;
}
}
if (LastAudioPartIndex == targetIndex) return;
if (partInfo == null || liveVocal == null ||
!partInfo.PartSettings.TryGetValue("time", out var times)) return;
int targetIndex = times.Count - 1;
while (targetIndex >= 0 && _liveCurrentTime < times[targetIndex] / 1000.0) targetIndex--;
if (targetIndex < 0 || (!forceUpdate && LastAudioPartIndex == targetIndex)) return;
LastAudioPartIndex = targetIndex;
float volume_rate = 1;
if (partInfo.PartSettings.ContainsKey("volume_rate"))
int activeCount = 0;
foreach (string part in OrderedParts)
{
volume_rate = partInfo.PartSettings["volume_rate"][targetIndex];
var vocal = FindVocal(liveVocal, part);
if (vocal != null && PartValue(partInfo, part, targetIndex, 0f) > 0f) activeCount++;
}
if (volume_rate == 999) //chorus
// Original AlterUpdate 0x1b8c31d and 0x1b8c562: >=900 means default,
// not zero. An explicit zero remains authored silence.
float rate = PartValue(partInfo, "volume_rate", targetIndex, 901f);
if (rate >= 900f) rate = activeCount < DefaultVolumeRates.Length ? DefaultVolumeRates[activeCount] : 1f;
int rank = 0;
foreach (string part in OrderedParts)
{
var activeVocal = new List<CuteAudioSource>();
for (int i = 0; i < liveVocal.Count; i++)
{
var vocal = liveVocal[i];
var partName = vocal.tag;
var active_index = (int)partInfo.PartSettings[partName][targetIndex];
vocal.SwitchActiveSource(active_index, forceUpdate);
if (partInfo.PartSettings.ContainsKey(partName + "_pan"))
{
var part = partInfo.PartSettings[partName + "_pan"];
var pan = part[targetIndex];
vocal.SetPanStereo(pan == 999 ? 0 : pan);
}
if (active_index > 0)
{
activeVocal.Add(vocal);
}
}
switch(activeVocal.Count)
{
case 1:
activeVocal[0].SetVolume(0.9954f);
break;
case 2:
activeVocal[0].SetVolume(0.7031f);
activeVocal[1].SetVolume(0.7031f);
break;
case 3:
activeVocal[0].SetVolume(0.7056f);
activeVocal[1].SetVolume(0.56f);
activeVocal[1].SetVolume(0.56f);
break;
default:
var per_vol = CalculateApproximateDBValues(0.9954f, activeVocal.Count);
activeVocal.ForEach(v => v.SetVolume(per_vol));
break;
}
var vocal = FindVocal(liveVocal, part);
if (vocal == null) continue;
int index = (int)PartValue(partInfo, part, targetIndex, 0f);
vocal.SwitchActiveSource(index, forceUpdate);
bool active = index > 0;
int row = activeCount < DefaultVolumeIndices.Length ? activeCount : 0;
int column = active && row > 0 ? rank++ : 0;
if (!active) row = 0;
float volume = PartValue(partInfo, part + "_vol", targetIndex, 901f);
float pan = PartValue(partInfo, part + "_pan", targetIndex, 901f);
if (volume >= 900f) volume = DefaultVolumes[DefaultVolumeIndices[row][column]];
if (pan >= 900f) pan = DefaultPans[row][column];
vocal.SetVolume(volume * rate);
vocal.SetPanStereo(pan);
}
else
{
for (int i = 0; i < liveVocal.Count; i++)
{
var vocal = liveVocal[i];
var partName = vocal.tag;
var active_index = (int)partInfo.PartSettings[partName][targetIndex];
vocal.SwitchActiveSource(active_index, forceUpdate);
if (partInfo.PartSettings.ContainsKey(partName))
{
if (partInfo.PartSettings.ContainsKey(partName + "_vol"))
{
var part = partInfo.PartSettings[partName + "_vol"];
var volume = part[targetIndex];
vocal.SetVolume(volume == 999 ? 0 : volume);
}
if (partInfo.PartSettings.ContainsKey(partName + "_pan"))
{
var part = partInfo.PartSettings[partName + "_pan"];
var pan = part[targetIndex];
vocal.SetPanStereo(pan == 999 ? 0 : pan);
}
}
}
}
}
static public float CalculateApproximateDBValues(float total_volume, int num_sounds)
static CuteAudioSource FindVocal(List<CuteAudioSource> vocals, string part)
{
var total_db = 15f;
var P0 = total_volume * (Math.Pow(10, total_db / 10));
var P_per_sound = P0 / num_sounds;
var per_volume = 10 * Math.Log10(P_per_sound / total_volume);
return (float)(per_volume / total_db);
for (int i = 0; i < vocals.Count; i++)
if (vocals[i].tag == part) return vocals[i];
return null;
}
static float PartValue(PartEntry data, string column, int row, float fallback)
{
return data.PartSettings.TryGetValue(column, out var values) && row < values.Count
? values[row] : fallback;
}
}
+18 -26
View File
@@ -1,4 +1,4 @@
using CriWareFormats;
using CriWareFormats;
using Gallop;
using Gallop.Live;
using Gallop.Live.Cutt;
@@ -841,20 +841,18 @@ public string[] NormalBodyKeywords = new[] { "skin", "body", "bdy", "face", "he
public void LoadLive(LiveEntry live, List<LiveCharacterSelect> characters)
{
characters.ForEach(a =>
if (!LiveAutoSelection.FillMissing(Main, live, characters, UI.CostumeIconDefault))
{
if (a.CharaEntry == null || string.IsNullOrEmpty(a.CostumeId))
{
a.CharaEntry = Main.Characters[Random.Range(0, Main.Characters.Count / 2)];
a.CostumeId = "0002_00_00";
}
});
UI.ShowMessage("Cannot fill the live selection: no available character-owned winning costume matches an empty slot.", UIMessageType.Error);
return;
}
// 在旧 UI 场景卸载前复制成普通 C# 数据。后续异步加载不会丢角色选择。
List<LiveCharacterLoadData> liveCharacters =
LiveCharacterLoadData.CaptureAll(characters);
bool requireStage = UI.isRequireStage;
int liveMode = UI.LiveMode;
// Opt-in diagnostics begin before root registration, then follow the
// exact dependency-expanded request count shown by the progress UI.
LiveRuntimeDiagnostics.BeginPreload(live, liveCharacters, requireStage);
@@ -912,26 +910,20 @@ public string[] NormalBodyKeywords = new[] { "skin", "body", "bdy", "face", "he
controller.Initialize();
LiveRuntimeDiagnostics.RecordPhase("director_initialized", controller);
int actualMemberCount = controller
._liveTimelineControl
.data
.worksheetList[0]
.charaMotSeqList
.Count;
if (actualMemberCount > liveCharacters.Count && liveCharacters.Count > 0)
// Native full-mode callback (RVA 0x1ba8981..0x1ba8b76) cycles
// selected identities through the raw authored channel count.
// Simple mode uses only the UI's basic-motion selection capacity.
int motionChannelCount = controller._liveTimelineControl.data.worksheetList[0].charaMotSeqList.Count;
if (liveMode == 1 && liveCharacters.Count > 0 && motionChannelCount > liveCharacters.Count)
{
Debug.LogWarning(
$"actual member count is {actualMemberCount} current {liveCharacters.Count}");
var expandedCharacters = new List<LiveCharacterLoadData>();
for (int i = 0; i < actualMemberCount; i++)
expandedCharacters.Add(liveCharacters[i % liveCharacters.Count]);
liveCharacters = expandedCharacters;
var channelCharacters = new List<LiveCharacterLoadData>(motionChannelCount);
for (int i = 0; i < motionChannelCount; i++)
channelCharacters.Add(liveCharacters[i % liveCharacters.Count]);
liveCharacters = channelCharacters;
}
LoadLiveUma(liveCharacters);
LiveRuntimeDiagnostics.RecordPhase("characters_loaded", controller);
@@ -989,7 +981,7 @@ public string[] NormalBodyKeywords = new[] { "skin", "body", "bdy", "face", "he
{
if (director == null) return;
director.InitializeUI();
director.InitializeTimeline(liveCharacters, UI.LiveMode);
director.InitializeTimeline(liveCharacters, liveMode);
director.InitializeMusic(live.MusicId, liveCharacters);
LiveRuntimeDiagnostics.RecordPhase("timeline_music_initialized", director);
director.Play();
+14 -9
View File
@@ -85,17 +85,18 @@ public class UmaViewerMain : MonoBehaviour
// Online English names take priority. LocalizeEn remains the offline fallback.
// Reuse downloaded English names; only fetch when no usable cache exists.
bool downloadTranslations = false;
string cachePath = Path.Combine(Application.persistentDataPath, EnglishNamesCacheFileName);
if (Config.Instance.Language == Language.En)
downloadTranslations = !TryLoadEnglishNamesCache(cachePath);
loadingUI.LoadingProgressChange(
loadingStep++,
loadingStepsTotal,
Config.Instance.Language == Language.En ? "Downloading Translations" : "Loading Translations");
if (Config.Instance.Language == Language.En)
downloadTranslations ? "Downloading Translations" : "Loading Translations");
if (downloadTranslations)
{
string cachePath = Path.Combine(
Application.persistentDataPath,
EnglishNamesCacheFileName);
TryLoadEnglishNamesCache(cachePath);
yield return UmaViewerDownload.DownloadText(LocalizeEn.TranslationUrl, json =>
{
@@ -284,9 +285,9 @@ public class UmaViewerMain : MonoBehaviour
}
}
private static void TryLoadEnglishNamesCache(string cachePath)
private static bool TryLoadEnglishNamesCache(string cachePath)
{
if (!File.Exists(cachePath)) return;
if (!File.Exists(cachePath)) return false;
try
{
@@ -301,13 +302,17 @@ public class UmaViewerMain : MonoBehaviour
Dictionary<int, string> charaNames = ReadEnglishNameTable(reader);
Dictionary<int, string> mobNames = ReadEnglishNameTable(reader);
if (charaNames.Count == 0 || mobNames.Count == 0)
throw new InvalidDataException("English name cache is missing required name tables.");
ApplyEnglishNames(charaNames, mobNames);
Debug.Log($"Loaded cached English names: {charaNames.Count} characters, {mobNames.Count} mobs.");
}
return true;
}
catch (Exception ex)
{
Debug.LogWarning($"Could not load the cached English names. Using LocalizeEn fallback: {ex.Message}");
return false;
}
}
+48 -101
View File
@@ -189,8 +189,9 @@ public class UmaViewerUI : MonoBehaviour
public IEnumerator ApplyGraphicsSettings()
{
yield return 0;
CameraSettings.ChangeAntiAliasing(Config.Instance.AntiAliasing);
CameraSettings.AAModeDropdown.SetValueWithoutNotify(Config.Instance.AntiAliasing);
GraphicsSettings.renderPipelineAsset = Config.Instance.Region == Region.Global ? null : UmaViewerMain.Instance.DefaultRenderPipeline;
RuntimeGraphicsSettings.Apply();
}
public void HighlightChildImage(Transform mainObject, UmaUIContainer child)
@@ -867,61 +868,60 @@ public class UmaViewerUI : MonoBehaviour
}
}
void ShowLiveSelectPanel(LiveEntry entry)
void ShowLiveSelectPanel(LiveEntry entry, bool loadPreview = true)
{
LiveSelectPannel.SetActive(true);
Builder.loadLivePreviewSound(entry.MusicId);
for (int i = LiveSelectList.content.childCount - 1; i >= 0; i--)
if (loadPreview) Builder.loadLivePreviewSound(entry.MusicId);
bool keepSelections = currentLive == entry;
CurrentSeletChara = null;
if (!keepSelections)
{
Destroy(LiveSelectList.content.GetChild(i).gameObject);
for (int i = LiveSelectList.content.childCount - 1; i >= 0; i--)
{
var child = LiveSelectList.content.GetChild(i);
child.SetParent(null);
Destroy(child.gameObject);
}
}
if(LiveMode == 1)
currentLive = entry;
LiveSelectImage.sprite = entry.Icon;
int memberCount = entry.MemberCount;
if (LiveMode == 0)
{
currentLive = entry;
LiveSelectImage.sprite = entry.Icon;
LiveSelectInfoText.text = $"{entry.SongName}\nMembers Count: {entry.MemberCount}";
for (int i = 0; i < entry.MemberCount; i++)
memberCount = Main.AbMotions.Count(a => a.Name.StartsWith($"3d/motion/live/body/son{entry.MusicId}") && Path.GetFileName(a.Name).Split('_').Length == 4);
LiveSelectInfoText.text = $"{entry.SongName}\nMain Members Count: {memberCount}";
}
else
{
LiveSelectInfoText.text = $"{entry.SongName}\nMembers Count: {memberCount}";
}
var selections = new List<LiveCharacterSelect>(LiveSelectList.content.GetComponentsInChildren<LiveCharacterSelect>());
for (int i = selections.Count - 1; i >= memberCount; i--)
{
selections[i].transform.SetParent(null);
Destroy(selections[i].gameObject);
selections.RemoveAt(i);
}
for (int i = selections.Count; i < memberCount; i++)
{
var chara = Instantiate(LiveSelectPrefab, LiveSelectList.content).GetComponent<LiveCharacterSelect>();
chara.IndexText.text = (i + 1).ToString();
chara.GetComponent<Button>().onClick.AddListener(() =>
{
var chara = Instantiate(LiveSelectPrefab, LiveSelectList.content).GetComponent<LiveCharacterSelect>();
chara.IndexText.text = (i + 1).ToString();
chara.GetComponent<Button>().onClick.AddListener(() =>
chara.SelectChara(this);
foreach (var t in LiveSelectList.content.GetComponentsInChildren<LiveCharacterSelect>())
{
chara.SelectChara(this);
foreach (var t in LiveSelectList.content.GetComponentsInChildren<LiveCharacterSelect>())
{
t.GetComponentInChildren<Text>().color = (t == chara ? Color.green : Color.black);
}
});
}
t.GetComponentInChildren<Text>().color = (t == chara ? (LiveMode == 1 ? Color.green : Color.white) : Color.black);
}
});
selections.Add(chara);
}
else if(LiveMode == 0)
{
currentLive = entry;
LiveSelectImage.sprite = entry.Icon;
int mainCount = 0;
foreach (var motion in Main.AbMotions.Where(a => a.Name.StartsWith($"3d/motion/live/body/son{entry.MusicId}") && Path.GetFileName(a.Name).Split('_').Length == 4))
{
mainCount += 1;
}
LiveSelectInfoText.text = $"{entry.SongName}\nMain Members Count: {mainCount}";
for (int i = 0; i < mainCount; i++)
{
var chara = Instantiate(LiveSelectPrefab, LiveSelectList.content).GetComponent<LiveCharacterSelect>();
chara.IndexText.text = (i + 1).ToString();
chara.GetComponent<Button>().onClick.AddListener(() =>
{
chara.SelectChara(this);
foreach (var t in LiveSelectList.content.GetComponentsInChildren<LiveCharacterSelect>())
{
t.GetComponentInChildren<Text>().color = (t == chara ? Color.white : Color.black);
}
});
}
}
foreach (var selection in selections)
selection.GetComponentInChildren<Text>().color = Color.black;
if (!LiveAutoSelection.FillMissing(Main, entry, selections, CostumeIconDefault))
ShowMessage("Cannot fill the live selection: no available character-owned winning costume matches an empty slot.", UIMessageType.Warning);
}
void ListCostumes(CharaEntry chara, bool mini)
@@ -1390,60 +1390,7 @@ public class UmaViewerUI : MonoBehaviour
{
LiveMode = val;
if (LiveSelectPannel.activeSelf && currentLive != null)
{
foreach (var select in LiveSelectList.content.GetComponentsInChildren<Transform>())
{
if (select != LiveSelectList.content.transform)
{
Destroy(select.gameObject);
}
}
switch (LiveMode)
{
case 0:
LiveSelectImage.sprite = currentLive.Icon;
int mainCount = 0;
foreach (var motion in Main.AbMotions.Where(a => a.Name.StartsWith($"3d/motion/live/body/son{currentLive.MusicId}") && Path.GetFileName(a.Name).Split('_').Length == 4))
{
mainCount += 1;
}
LiveSelectInfoText.text = $"{currentLive.SongName}\nMain Members Count: {mainCount}";
for (int i = 0; i < mainCount; i++)
{
var chara = Instantiate(LiveSelectPrefab, LiveSelectList.content).GetComponent<LiveCharacterSelect>();
chara.IndexText.text = (i + 1).ToString();
chara.GetComponent<Button>().onClick.AddListener(() =>
{
chara.SelectChara(this);
foreach (var t in LiveSelectList.content.GetComponentsInChildren<LiveCharacterSelect>())
{
t.GetComponentInChildren<Text>().color = (t == chara ? Color.white : Color.black);
}
});
}
break;
case 1:
LiveSelectImage.sprite = currentLive.Icon;
LiveSelectInfoText.text = $"{currentLive.SongName}\nMembers Count: {currentLive.MemberCount}";
for (int i = 0; i < currentLive.MemberCount; i++)
{
var chara = Instantiate(LiveSelectPrefab, LiveSelectList.content).GetComponent<LiveCharacterSelect>();
chara.IndexText.text = (i + 1).ToString();
chara.GetComponent<Button>().onClick.AddListener(() =>
{
chara.SelectChara(this);
foreach (var t in LiveSelectList.content.GetComponentsInChildren<LiveCharacterSelect>())
{
t.GetComponentInChildren<Text>().color = (t == chara ? Color.white : Color.black);
}
});
}
break;
}
}
ShowLiveSelectPanel(currentLive, false);
}
public void SetLiveRecordMode(bool val) { isRecordVMD = val; }
@@ -1,4 +1,4 @@
using Gallop.ImageEffect;
using Gallop.ImageEffect;
using Gallop.RenderPipeline;
using UnityEngine;
@@ -14,6 +14,15 @@ namespace Gallop
public DofDiffusionBloomOverlayParam DofDiffusionBloomOverlayParam => _dofDiffusionBloomOverlayParam;
public bool IsInitialized { get; private set; }
private CameraData _cameraData;
public PostImageEffectFeature.Parameter RenderParameter
{
get
{
if (!IsInitialized) InitializeVolume();
return _cameraData.Parameter;
}
}
// 子系统 A7b:原生 GallopImageEffect.get_ExposureParam(RVA=0x19a97b0) /
// get_ToneCurveParam(RVA=0x19a9930) 的 master7 等价属性。原生 getter 返回
@@ -39,10 +48,16 @@ namespace Gallop
if (adapter != null) adapter.ApplyBloomParameter();
}
private void Awake() { InitializeVolume(); }
protected void Awake() { InitializeVolume(); }
// Retained for existing callers; no spatial Volume is created.
public void InitializeVolume() { IsInitialized = true; }
public virtual void InitializeVolume()
{
if (IsInitialized) return;
if (!TryGetComponent(out _cameraData))
_cameraData = gameObject.AddComponent<CameraData>();
IsInitialized = true;
}
public void ApplyBloomParameter()
{
@@ -50,24 +65,18 @@ namespace Gallop
if (director == null || director.MainRenderCamera == null ||
director.MainRenderCamera.gameObject != gameObject) return;
var parameter = PostImageEffectFeature.RuntimeParameter;
var parameter = RenderParameter;
PostImageEffectFeature.RuntimeParameter = parameter;
parameter.DofDiffuionBloomOverlay.Setup(_dofDiffusionBloomOverlayParam);
if (!UserDofEnabled)
{
parameter.DofDiffuionBloomOverlay.IsEnableDof = false;
parameter.DofDiffuionBloomOverlay.IsEnableOldDof = false;
}
parameter.DofDiffuionBloomOverlay.DecideDrawType(
UserDofEnabled && _dofDiffusionBloomOverlayParam.IsEnableDof);
_cameraData.UpdateImageEffectParameter();
parameter.TargetCamera = director.MainRenderCamera;
// 子系统 A7b:原生 CameraData.UpdateImageEffectParameter(RVA=0x1a0da30)
// 末尾 jmp Parameter.DecideDrawType,把 GallopImageEffect 的参数块
//(DOF + Exposure + ToneCurve…)统一交给渲染侧。master7 的
// PostImageEffectFeature.Parameter 还没有 Exposure/ToneCurve 的
// pass 消费字段,因此先挂在运行时参数对象上供后续
// ExposurePass/ToneCurvePass(原生 RVA=0x1a22e10/0x1a527d0)接入,
// 数据已随时间轴逐帧刷新,不会比原生缺帧。
// Exposure and tone curves publish into the same camera-owned render state.
parameter.ExposureParam.Setup(ExposureParam);
parameter.ToneCurveParam.Setup(ToneCurveParam);
}
@@ -0,0 +1,15 @@
namespace Gallop
{
// Serialized Live camera subtype. The base image effect is also used outside Live.
public class LiveImageEffect : GallopImageEffect
{
public override void InitializeVolume()
{
if (IsInitialized) return;
base.InitializeVolume();
// Actual game Initialize RVA 0x7395c80 calls the base initializer,
// then writes render Parameter+0x1b=true (0x7395ced). Not source Setup.
RenderParameter.DofDiffuionBloomOverlay.IsEnableDofAutoDisable = true;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 428adbfbca84b7e49a12cc841c2928b3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
@@ -331,7 +331,7 @@ namespace Gallop.Live.Cutt
public event HdrBloomUpdateInfoDelegate OnUpdateHdrBloom;
public event Action<PostEffectUpdateInfo_BloomDiffusion> OnUpdatePostEffect_BloomDiffusion;
public event Action<LiveTimelineKeyPostEffectDOFData> OnUpdatePostEffect_Dof;
public event Action<LiveTimelineKeyPostEffectDOFData, Vector3?> OnUpdatePostEffect_Dof;
public bool HasDofCameraLookAt { get; private set; }
public Vector3 DofCameraLookAt { get; private set; }
public Camera DofTrackCamera { get; private set; }
@@ -395,6 +395,7 @@ namespace Gallop.Live.Cutt
public event Action RecordUma;
public Dictionary<string, GameObject> StageObjectMap = new Dictionary<string, GameObject>();
public Dictionary<string, StageObjectUnit> StageObjectUnitMap = new Dictionary<string, StageObjectUnit>();
public float currentLiveTime
{
@@ -553,16 +554,18 @@ namespace Gallop.Live.Cutt
public void InitCharaMotionSequence(int[] motionSequence)
{
//Create Animation
foreach (var obj in Director.instance.charaObjs)
var director = Director.instance;
// Native InitCharaMotionSequence retains an entry for each physical slot.
foreach (var obj in director.charaObjs)
{
var container = obj.GetComponentInChildren<UmaContainer>();
if (container)
var container = obj != null ? obj.GetComponentInChildren<UmaContainer>() : null;
Animation animation = null;
if (container != null)
{
EnsureMicMotionTransforms(container.transform);
var animation = container.gameObject.AddComponent<Animation>();
Director.instance.charaAnims.Add(animation);
animation = container.gameObject.AddComponent<Animation>();
}
director.charaAnims.Add(animation);
}
//Get KeyArray
@@ -578,14 +581,14 @@ namespace Gallop.Live.Cutt
if (Director.instance.liveMode == 1)
{
//Set Motion
int CharaPositionMax = Director.instance.allowCount;
int CharaPositionMax = Mathf.Max(0, Mathf.Min(director.allowCount,
Mathf.Min(director.charaObjs.Count, motionSequence != null ? motionSequence.Length : 0)));
_motionSequenceArray = new LiveTimelineMotionSequence[CharaPositionMax];
for (int i = 0; i < CharaPositionMax; i++)
{
Debug.Log(i);
_motionSequenceArray[i] = new LiveTimelineMotionSequence();
_motionSequenceArray[i].Initialize(Director.instance.charaObjs[i], i, motionSequence[i], this);
}
@@ -597,7 +600,10 @@ namespace Gallop.Live.Cutt
foreach (var motion in UmaViewerMain.Instance.AbMotions.Where(a => a.Name.StartsWith($"3d/motion/live/body/son{Director.instance.live.MusicId}") && Path.GetFileName(a.Name).Split('_').Length == 4))
{
AssetBundle motionAB = UmaAssetManager.LoadAssetBundle(motion);
AnimationClip motionAnim = motionAB.LoadAsset<AnimationClip>(Path.GetFileName(motion.Name).Split('.')[0]);
AnimationClip motionAnim = motionAB != null
? motionAB.LoadAsset<AnimationClip>(Path.GetFileName(motion.Name).Split('.')[0]) : null;
if (motionAnim == null)
Debug.LogError("[LiveTimelineControl] Basic motion clip load failed: " + motion.Name);
if (Gallop.Live.LiveRuntimeDiagnostics.Enabled)
Gallop.Live.LiveRuntimeDiagnostics.RecordAssetLoad(motion.Name, "LoadAsset", typeof(AnimationClip),
new UnityEngine.Object[] { motionAnim }, motionAnim, Path.GetFileName(motion.Name).Split('.')[0]);
@@ -605,7 +611,8 @@ namespace Gallop.Live.Cutt
}
//Set Motion
int CharaPositionMax = Director.instance.allowCount;
int CharaPositionMax = Mathf.Max(0, Mathf.Min(director.allowCount,
Mathf.Min(director.charaObjs.Count, Mathf.Min(director.charaAnims.Count, Anims.Count))));
_motionSequenceArray = new LiveTimelineMotionSequence[CharaPositionMax];
@@ -613,7 +620,7 @@ namespace Gallop.Live.Cutt
for (int i = 0; i < CharaPositionMax; i++)
{
_motionSequenceArray[i] = new LiveTimelineMotionSequence();
_motionSequenceArray[i].Initialize(Director.instance.charaObjs[i], i, motionSequence[i], this, Anims);
_motionSequenceArray[i].Initialize(director.charaObjs[i], i, i, this, Anims);
}
}
@@ -1585,26 +1592,15 @@ namespace Gallop.Live.Cutt
LiveTimelineKeyCameraPositionData liveTimelineKeyCameraPositionData = curKey as LiveTimelineKeyCameraPositionData;
camera.camera.nearClipPlane = liveTimelineKeyCameraPositionData.nearClip;
camera.camera.farClipPlane = liveTimelineKeyCameraPositionData.farClip;
// Native AlterUpdate_CameraPos (0x1acd38c..0x1acd3f4) preserves unflagged state.
if (((int)liveTimelineKeyCameraPositionData.attribute & 0x20000) != 0)
camera.camera.cullingMask = liveTimelineKeyCameraPositionData.GetCullingMask();
if (((int)liveTimelineKeyCameraPositionData.attribute & 0x40000) != 0)
camera.camera.backgroundColor = liveTimelineKeyCameraPositionData.BgColor;
if (CalculateCameraPos(out var pos, sheet, curKey, nextKey, currentFrame))
{
camera.cacheTransform.position = pos;
// TODO 锟斤拷锟斤拷锟矫的伙拷锟斤拷CGSS锟斤拷layer枚锟劫o拷要锟斤拷锟斤拷锟芥换
/*
int num = liveTimelineKeyCameraPositionData.GetCullingMask();
if (num == 0)
{
num = LiveTimelineKeyCameraPositionData.GetDefaultCullingMask();
}
camera.camera.cullingMask = num;
if (OnUpdateCameraPos != null)
{
CameraPosUpdateInfo updateInfo = default(CameraPosUpdateInfo);
updateInfo.outlineZOffset = liveTimelineKeyCameraPositionData.outlineZOffset;
updateInfo.characterLODMask = (int)liveTimelineKeyCameraPositionData.characterLODMask;
OnUpdateCameraPos(ref updateInfo);
}
*/
}
}
@@ -2440,7 +2436,7 @@ namespace Gallop.Live.Cutt
private void AlterUpdate_MobControl(LiveTimelineWorkSheet sheet, float currentFrame)
{
AlterUpdate_MobCyalumeControl(
sheet != null ? sheet.mobControlList : null,
sheet != null ? sheet.MobControlKeys : null,
currentFrame,
OnUpdateMobControl);
}
@@ -2448,7 +2444,7 @@ namespace Gallop.Live.Cutt
private void AlterUpdate_CyalumeControl(LiveTimelineWorkSheet sheet, float currentFrame)
{
AlterUpdate_MobCyalumeControl(
sheet != null ? sheet.cyalumeControlList : null,
sheet != null ? sheet.CyalumeControlKeys : null,
currentFrame,
OnUpdateCyalumeControl);
}
@@ -2465,10 +2461,10 @@ namespace Gallop.Live.Cutt
for (int i = 0; i < count; i++)
{
var controlData = dataList[i];
if (controlData == null || controlData.keys == null)
if (controlData == null || controlData.Keys == null || (uint)controlData.GroupIndex >= 11u)
continue;
var keys = controlData.keys;
var keys = controlData.Keys;
if (keys.Count <= 0)
continue;
if (keys.HasAttribute(LiveTimelineKeyDataListAttr.Disable))
@@ -2485,22 +2481,22 @@ namespace Gallop.Live.Cutt
MobCyalumeUpdateInfo info = default;
info.data = controlData;
info.unk0 = (uint)keys.unk48 < 11u ? keys.unk48 : i;
info.unk0 = controlData.GroupIndex;
info.currentFrame = currentFrame;
info.currentLiveTime = currentLiveTime;
if (next != null && next.interpolateType != 0)
{
float t = CalculateInterpolationValue(current, next, currentFrame);
info.position = Vector3.Lerp(current.position, next.position, t);
info.position = Vector3.Lerp(current.Position, next.Position, t);
info.rotation = Quaternion.Lerp(current.GetRotation(), next.GetRotation(), t);
info.scale = Vector3.Lerp(current.scale, next.scale, t);
info.scale = Vector3.Lerp(current.Scale, next.Scale, t);
}
else
{
info.position = current.position;
info.position = current.Position;
info.rotation = current.GetRotation();
info.scale = current.scale;
info.scale = current.Scale;
}
callback.Invoke(ref info);
@@ -2975,7 +2971,8 @@ namespace Gallop.Live.Cutt
continue;
}
if (StageObjectMap == null || !StageObjectMap.ContainsKey(objectEntry.name))
if ((StageObjectMap == null || !StageObjectMap.ContainsKey(objectEntry.name)) &&
(StageObjectUnitMap == null || !StageObjectUnitMap.ContainsKey(objectEntry.name)))
continue;
FindTimelineKey(out var curKey, out var nextKey, keys, currentFrame);
@@ -3207,6 +3204,27 @@ namespace Gallop.Live.Cutt
}
}
private Vector3? ResolveDofWorldFocus(LiveTimelineKeyPostEffectDOFData key)
{
if (((int)key.attribute & (1 << 16)) != 0)
return HasDofCameraLookAt ? DofCameraLookAt : (Vector3?)null;
bool valid = key.charactor == 0;
for (int i = 0; !valid && i < liveCharactorLocators.Length && i < liveCharaPositionMax; ++i)
valid = (key.charactor & (1 << i)) != 0 && liveCharactorLocators[i] != null;
return valid ? GetPositionWithCharacters(key.FocusCharacters, LiveCameraCharaParts.Face,
Vector3.zero, Vector3.zero) : (Vector3?)null;
}
private Vector3? SetupDofWorldFocus(LiveTimelineKeyPostEffectDOFData current,
LiveTimelineKeyPostEffectDOFData next, float progress)
{
var start = ResolveDofWorldFocus(current);
if (ReferenceEquals(current, next)) return start;
var end = ResolveDofWorldFocus(next);
return start.HasValue && end.HasValue
? Vector3.LerpUnclamped(start.Value, end.Value, progress) : (Vector3?)null;
}
private void AlterUpdate_PostEffect_Dof(LiveTimelineWorkSheet sheet, int frame)
{
DofTrackCamera = GetCamera(sheet.targetCameraIndex)?.camera;
@@ -3214,32 +3232,32 @@ namespace Gallop.Live.Cutt
if (keys == null || keys.HasAttribute(LiveTimelineKeyDataListAttr.Disable) ||
!keys.EnablePlayModeTimeline(_playMode))
{
OnUpdatePostEffect_Dof?.Invoke(null);
OnUpdatePostEffect_Dof?.Invoke(null, null);
return;
}
FindTimelineKey(out var currentBase, out var nextBase, keys, frame);
var current = currentBase as LiveTimelineKeyPostEffectDOFData;
var next = nextBase as LiveTimelineKeyPostEffectDOFData;
if (current == null) { OnUpdatePostEffect_Dof?.Invoke(null); return; }
if (current == null) { OnUpdatePostEffect_Dof?.Invoke(null, null); return; }
float t = next != null && next.IsInterpolateKey()
? CalculateInterpolationValue(current, next, frame) : 0f;
if (next == null) next = current;
if (next == null || !next.IsInterpolateKey()) next = current;
var sample = _dofSample;
sample.frame = current.frame;
sample.attribute = current.attribute;
sample.charactor = current.charactor;
sample.dofBlurType = current.dofBlurType;
sample.dofQuality = current.dofQuality;
sample.forcalSize = Mathf.Lerp(current.forcalSize, next.forcalSize, t);
sample.blurSpread = Mathf.Lerp(current.blurSpread, next.blurSpread, t);
sample.dofForegroundSize = Mathf.Lerp(current.dofForegroundSize, next.dofForegroundSize, t);
sample.dofFocalPoint = Mathf.Lerp(current.dofFocalPoint, next.dofFocalPoint, t);
sample.dofSmoothness = Mathf.Lerp(current.dofSmoothness, next.dofSmoothness, t);
sample.BallBlurPowerFactor = Mathf.Lerp(current.BallBlurPowerFactor, next.BallBlurPowerFactor, t);
sample.BallBlurBrightnessThreshhold = Mathf.Lerp(current.BallBlurBrightnessThreshhold, next.BallBlurBrightnessThreshhold, t);
sample.BallBlurBrightnessIntensity = Mathf.Lerp(current.BallBlurBrightnessIntensity, next.BallBlurBrightnessIntensity, t);
sample.BallBlurSpread = Mathf.Lerp(current.BallBlurSpread, next.BallBlurSpread, t);
OnUpdatePostEffect_Dof?.Invoke(sample);
sample.forcalSize = LerpWithoutClamp(current.forcalSize, next.forcalSize, t);
sample.blurSpread = LerpWithoutClamp(current.blurSpread, next.blurSpread, t);
sample.dofForegroundSize = LerpWithoutClamp(current.dofForegroundSize, next.dofForegroundSize, t);
sample.dofFocalPoint = LerpWithoutClamp(current.dofFocalPoint, next.dofFocalPoint, t);
sample.dofSmoothness = LerpWithoutClamp(current.dofSmoothness, next.dofSmoothness, t);
sample.BallBlurPowerFactor = LerpWithoutClamp(current.BallBlurPowerFactor, next.BallBlurPowerFactor, t);
sample.BallBlurBrightnessThreshhold = LerpWithoutClamp(current.BallBlurBrightnessThreshhold, next.BallBlurBrightnessThreshhold, t);
sample.BallBlurBrightnessIntensity = LerpWithoutClamp(current.BallBlurBrightnessIntensity, next.BallBlurBrightnessIntensity, t);
sample.BallBlurSpread = LerpWithoutClamp(current.BallBlurSpread, next.BallBlurSpread, t);
OnUpdatePostEffect_Dof?.Invoke(sample, SetupDofWorldFocus(current, next, t));
}
private void AlterUpdate_PostEffect_BloomDiffusion( LiveTimelineWorkSheet sheet, int currentFrame)
@@ -225,6 +225,9 @@ namespace Gallop.Live.Cutt
public float maxForcalSize;
public bool isUseMirrorScanMotionDictionary;
public bool isUseGameSettingToParticle;
public bool IsChangedCharaLayerOnlyMirrorRendering;
public bool IsRenderMirrorObjectOnlyOnBaseCamera;
public bool UseDepthOnlyCube;
public LiveTimelineStageObjectsSettings stageObjectsSettings;
public LiveTimelineDebugSettings debugSettings;
}
@@ -10,9 +10,9 @@ namespace Gallop.Live.Cutt
{
get{return LiveTimelineKeyDataType.CyalumeControl;}
}
public Vector3 position;
public Vector3 angle;
public Vector3 scale = Vector3.one;
public Vector3 Position;
public Vector3 Angle;
public Vector3 Scale = Vector3.one;
[NonSerialized]
private Quaternion _rotationCache = Quaternion.identity;
@@ -24,7 +24,7 @@ namespace Gallop.Live.Cutt
{
if (!_hasRotationCache)
{
_rotationCache = Quaternion.Euler(angle);
_rotationCache = Quaternion.Euler(Angle);
_hasRotationCache = true;
}
@@ -35,13 +35,13 @@ namespace Gallop.Live.Cutt
[Serializable]
public class LiveTimelineKeyMobCyalumeControlDataList : LiveTimelineKeyDataListTemplate<LiveTimelineKeyMobCyalumeControlData>
{
public int unk48;
}
[Serializable]
public class LiveTimelineMobCyalumeControlData : ILiveTimelineGroupDataWithName
{
public LiveTimelineKeyMobCyalumeControlDataList keys;
public int GroupIndex;
public LiveTimelineKeyMobCyalumeControlDataList Keys;
}
public delegate void MobCyalumeUpdateInfoDelegate(ref MobCyalumeUpdateInfo updateInfo);
@@ -34,17 +34,11 @@ namespace Gallop.Live.Cutt
/// </summary>
public LiveCharaPositionFlag FocusCharacters => (LiveCharaPositionFlag)charactor;
// High `attribute` bits are per-track flags (same convention as
// LiveTimelineMonitorData). Across the 4427 authored keys only bits 16..19
// appear, in the combinations 0x50000 (3117), 0x70000 (923), 0x60000 (108),
// 0x10000 (106), 0x40000 (77), 0x30000 (72), 0x20000 (22), 0x00000 (1) and
// 0xF0000 (1). Bit 17 covaries with an authored dofFocalPoint: 95.1% of the
// 3301 bit17-clear keys leave it at the 1.0 default, while 88.1% of the 1126
// bit17-set keys carry a real distance. Bit 16 covaries the other way with
// `charactor`: only 1.4% of the 4219 bit16-set keys move it off Center,
// against 56.7% of the 208 bit16-clear keys. The flag names are still
// unknown. Timeline mode tests the inferred bit17=metric / bit16=camera
// target mapping; see docs/LIVE_DOF_TIMELINE_2026-09-06.md for pixel evidence.
// Actual game metadata and SetupDOFUpdateInfo RVA 0x726a610 confirm:
// bit16 ATTR_USE_LOOKAT; bit17 ATTR_USE_FOCAL_POINT;
// bit18 ATTR_ENABLE_DOF; bit19 ATTR_IS_POINT_BALL_BLUR.
// Current-key flags select the mode; both endpoints resolve world focus
// independently before the next key's unclamped interpolation is applied.
}
[Serializable]
@@ -1,6 +1,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using RootMotion.FinalIK;
@@ -43,56 +44,96 @@ namespace Gallop.Live.Cutt
public void Initialize(Transform target, int targetIndex, int seqDataIndex, LiveTimelineControl timelineControl, List<AnimationClip> animclips = null)
{
if(animclips != null)
{
if (targetIndex < Director.instance.charaAnims.Count)
{
_targetAnim = animclips[targetIndex];
_tempAnim = Director.instance.charaAnims[targetIndex];
_tempAnim.AddClip(_targetAnim, _targetAnim.name);
}
var animations = Director.instance.charaAnims;
if (targetIndex < 0 || targetIndex >= animations.Count || animations[targetIndex] == null)
return;
}
_tempTarget = target;
_targetIndex = targetIndex;
charaIndex = targetIndex;
_tempAnim = animations[targetIndex];
if (animclips != null)
{
if (targetIndex >= animclips.Count) return;
_targetAnim = animclips[targetIndex];
if (_targetAnim != null) _tempAnim.AddClip(_targetAnim, _targetAnim.name);
return;
}
_keyArray = timelineControl._keyArray;
if (seqDataIndex < _keyArray.Length)
if (seqDataIndex < 0 || seqDataIndex >= _keyArray.Length) return;
_currentKey = _keyArray[seqDataIndex];
_sampleIk = _tempAnim.GetComponent<BipedIK>();
if (_sampleIk != null)
{
_currentKey = _keyArray[seqDataIndex];
// SolverManager.Update otherwise restores the bind pose after our manual sample.
_resetIkBeforeSample = _sampleIk.fixTransforms;
if (_resetIkBeforeSample) _sampleIk.fixTransforms = false;
}
if (targetIndex < Director.instance.charaAnims.Count)
{
_tempAnim = Director.instance.charaAnims[targetIndex];
_sampleIk = _tempAnim.GetComponent<BipedIK>();
if (_sampleIk != null)
{
// SolverManager.Update otherwise restores the bind pose after our manual sample.
_resetIkBeforeSample = _sampleIk.fixTransforms;
if (_resetIkBeforeSample) _sampleIk.fixTransforms = false;
}
}
if(_currentKey != null && _tempAnim != null)
if (_currentKey != null)
{
foreach (var key in _currentKey.thisList)
{
if(key.clip != null)
{
_tempAnim.AddClip(key.clip, key.clip.name);
}
}
SetupAnimationClip(key);
}
_tempAnim.wrapMode = WrapMode.Clamp;
_tempAnim.enabled = false;
}
private void SetupAnimationClip(LiveTimelineKeyCharaMotionData key)
{
// Native SetupAnimationClip (0x1af9ed0) ignores unnamed main-motion keys.
if (key == null || string.IsNullOrEmpty(key.motionName)) return;
// Native LoadAnimationClip (0x1ae4780) uses the existing clip triplet first.
if (key.clip == null)
{
key.clip = LoadLiveAnimationClip(key.motionName, key.clip);
key.clip2 = LoadLiveAnimationClip(key.motionName2, key.clip2);
key.clip3 = LoadLiveAnimationClip(key.motionName3, key.clip3);
}
if (key.clip != null) _tempAnim.AddClip(key.clip, key.clip.name);
if (key.clip2 != null) _tempAnim.AddClip(key.clip2, key.clip2.name);
if (key.clip3 != null) _tempAnim.AddClip(key.clip3, key.clip3.name);
}
private static AnimationClip LoadLiveAnimationClip(string motionName, AnimationClip existingClip)
{
if (existingClip != null || string.IsNullOrEmpty(motionName)) return existingClip;
// ResourcePath.GetLiveAnimationClipPath: original body motion, not a substitute action.
string path = "3d/motion/live/body/" + motionName;
var entry = LiveEffectController.FindResourceEntry(path);
if (entry == null)
{
Debug.LogError("[LiveTimelineMotionSequence] Motion resource not found: " + path);
return null;
}
var bundle = UmaAssetManager.LoadAssetBundle(entry);
if (bundle == null)
{
Debug.LogError("[LiveTimelineMotionSequence] Motion bundle load failed: " + path);
return null;
}
string assetName = Path.GetFileNameWithoutExtension(entry.Name);
var clip = bundle.LoadAsset<AnimationClip>(assetName);
if (clip == null)
{
foreach (string asset in bundle.GetAllAssetNames())
{
if (!string.Equals(Path.GetFileNameWithoutExtension(asset), assetName, StringComparison.OrdinalIgnoreCase))
continue;
clip = bundle.LoadAsset<AnimationClip>(asset);
break;
}
}
if (LiveRuntimeDiagnostics.Enabled)
LiveRuntimeDiagnostics.RecordAssetLoad(entry.Name, "LoadAsset", typeof(AnimationClip),
new UnityEngine.Object[] { clip }, clip, assetName);
if (clip == null)
Debug.LogError("[LiveTimelineMotionSequence] Motion clip load failed: " + path + " (" + assetName + ")");
return clip;
}
public void AlterUpdate(float currentTime, LiveTimelineKeyTimescaleDataList timescaleKeys)
{
var director = Director.instance;
@@ -122,6 +163,7 @@ namespace Gallop.Live.Cutt
_curIndex = curKey.index;
LiveTimelineKeyCharaMotionData arg = curKey.key as LiveTimelineKeyCharaMotionData;
if (arg == null || string.IsNullOrEmpty(arg.motionName) || arg.clip == null) return;
AnimationClip anim = arg.clip;
double start;
@@ -172,13 +172,11 @@ namespace Gallop.Live.Cutt
public bool newBezierCalcMethod;
public CullingLayer cullingMask = defCameraCullingLayer;
public float outlineZOffset = 1f;
public CharacterLOD characterLODMask = (CharacterLOD)((uint)outlineLODMask + (uint)shaderLODMask);
protected const CullingLayer defCameraCullingLayer = (CullingLayer)0x7FE;
protected const CharacterLOD outlineLODMask = (CharacterLOD)0x3FF;
@@ -186,92 +184,21 @@ namespace Gallop.Live.Cutt
public int GetCullingMask()
{
return GetCullingMask(cullingMask);
}
protected static int GetCullingMask(CullingLayer layer)
{
int num = 257;
if ((layer & CullingLayer.TransparentFX) != 0)
{
num |= 2;
}
if ((layer & CullingLayer.Background3D_NotReflect) != 0)
{
num |= 0x80000;
}
if ((layer & CullingLayer.Background3d) != 0)
{
num |= 0x100000;
}
if ((layer & CullingLayer.Character3d) != 0)
{
num |= 0x200000;
}
if ((layer & CullingLayer.Character3d_0) != 0)
{
num |= 0x400000;
}
if ((layer & CullingLayer.Character3d_1) != 0)
{
num |= 0x800000;
}
if ((layer & CullingLayer.Character3d_2) != 0)
{
num |= 0x1000000;
}
if ((layer & CullingLayer.Character3d_3) != 0)
{
num |= 0x2000000;
}
if ((layer & CullingLayer.Character3d_4) != 0)
{
num |= 0x4000000;
}
if ((layer & CullingLayer.Character3D_NotReflect) != 0)
{
num |= 0x8000000;
}
if ((layer & CullingLayer.Background3D_Other) != 0)
{
num |= 0x40000;
}
return num;
/*
uint bittest = (uint)layer;
uint result = (uint)LayerMask.GetMask("Default");
if ((bittest & (uint)CullingLayer.TransparentFX) > 0)
result |= (uint)LayerMask.GetMask("TransparentFX");
if ((bittest & (uint)CullingLayer.Background3D_NotReflect) > 0)
result |= (uint)LayerMask.GetMask("background_NotReflect");
if ((bittest & (uint)CullingLayer.Background3d) > 0)
result |= (uint)LayerMask.GetMask("background");
if ((bittest & (uint)CullingLayer.Character3d) > 0)
result |= (uint)LayerMask.GetMask("charas");
if ((bittest & (uint)CullingLayer.Character3d_0) > 0)
result |= (uint)LayerMask.GetMask("chara1");
if ((bittest & (uint)CullingLayer.Character3d_1) > 0)
result |= (uint)LayerMask.GetMask("chara2");
if ((bittest & (uint)CullingLayer.Character3d_2) > 0)
result |= (uint)LayerMask.GetMask("chara3");
if ((bittest & (uint)CullingLayer.Character3d_3) > 0)
result |= (uint)LayerMask.GetMask("chara4");
if ((bittest & (uint)CullingLayer.Character3d_4) > 0)
result |= (uint)LayerMask.GetMask("chara5");
if ((bittest & (uint)CullingLayer.Character3D_NotReflect) > 0)
result |= (uint)LayerMask.GetMask("otherChara");
if ((bittest & (uint)CullingLayer.Background3D_Other) > 0)
result |= (uint)LayerMask.GetMask("background_Other");
return (int)result;
*/
}
public static int GetDefaultCullingMask()
{
return GetCullingMask(defCameraCullingLayer);
// Native GetCullingMask (0x1af50a0) reads cullingLayer, not the legacy CGSS mask.
int mask = 0;
if ((cullingLayer & LiveCameraCullingLayer.TransparentFX) != 0) mask |= 1 << 1;
if ((cullingLayer & LiveCameraCullingLayer.Effect) != 0) mask |= 1 << 11;
if ((cullingLayer & LiveCameraCullingLayer.Background3d_NotReflect) != 0) mask |= 1 << 25;
if ((cullingLayer & LiveCameraCullingLayer.Background3d) != 0) mask |= 1 << 12;
if ((cullingLayer & LiveCameraCullingLayer.Character3d) != 0) mask |= 1 << 13;
if ((cullingLayer & LiveCameraCullingLayer.Character3d_0) != 0) mask |= 1 << 27;
if ((cullingLayer & LiveCameraCullingLayer.Character3d_1) != 0) mask |= 1 << 28;
if ((cullingLayer & LiveCameraCullingLayer.Character3d_NotReflect) != 0) mask |= 1 << 26;
if ((cullingLayer & LiveCameraCullingLayer.NotLayerDefault) == 0)
mask |= GraphicSettings.GetCullingLayer(GraphicSettings.LayerIndex.LayerDefault);
if ((cullingLayer & LiveCameraCullingLayer.NotLayer3d) == 0)
mask |= GraphicSettings.GetCullingLayer(GraphicSettings.LayerIndex.Layer3D);
return mask;
}
public virtual Vector3 GetValue(LiveTimelineControl timelineControl)
@@ -498,8 +425,8 @@ namespace Gallop.Live.Cutt
[SerializeField] public List<LiveTimelineTransformData> transformList;
[SerializeField] public List<LiveTimelineObjectData> objectList;
[SerializeField] public List<LiveTimelineMobCyalumeControlData> mobControlList;
[SerializeField] public List<LiveTimelineMobCyalumeControlData> cyalumeControlList;
[SerializeField] public List<LiveTimelineMobCyalumeControlData> MobControlKeys;
[SerializeField] public List<LiveTimelineMobCyalumeControlData> CyalumeControlKeys;
private void OnEnable()
{
@@ -303,6 +303,7 @@ namespace Gallop.Live.Cyalume
_mobShadowController = mobRoot.AddComponent<MobShadowController>();
_mobShadowController.Initialize(mobRoot);
_mobShadowController.FlushGroupMatrix();
_mobShadowController.SetMobColor(_mobColor);
_mobShadowController.SetAmbientColor(_mobAmbientColor);
@@ -340,8 +341,8 @@ namespace Gallop.Live.Cyalume
if ((uint)info.unk0 < 11u)
return info.unk0;
if (info.data != null && info.data.keys != null && (uint)info.data.keys.unk48 < 11u)
return info.data.keys.unk48;
if (info.data != null && (uint)info.data.GroupIndex < 11u)
return info.data.GroupIndex;
return -1;
}
+120 -97
View File
@@ -19,10 +19,11 @@ namespace Gallop.Live
[SerializeField]
private GameObject[] _cameraNodes;
private Camera[] _cameraObjects;
private GallopImageEffect[] _cameraImageEffects;
private Transform[] _cameraTransforms;
[SerializeField]
private CameraLookAt _cameraLookAt;
private int _activeCameraIndex = 1;
private int _activeCameraIndex = 1;
private readonly int[] kTimelineCameraIndices = new int[3] { 1, 2, 3 };
[SerializeField] private bool _enableMirrorReflection = true;
[SerializeField] private List<MirrorReflection> _mirrorReflections = new List<MirrorReflection>();
@@ -280,9 +281,10 @@ namespace Gallop.Live
}
Builder.LoadAssetPath(stagePath, transform);
_liveTimelineControl.StageObjectMap = _stageController.StageObjectMap;
_liveTimelineControl.StageObjectUnitMap = _stageController.StageObjectUnitMap;
}
@@ -308,7 +310,8 @@ namespace Gallop.Live
charaObjs.Add(newObj.transform);
counter++;
}
};
}
;
//Get live parts info
@@ -397,20 +400,20 @@ namespace Gallop.Live
foreach (var renderer in container.Renderers)
{
renderer.GetPropertyBlock(propertyBlock);
propertyBlock.SetFloat("_RimShadowRate", updateInfo.globalRimShadowRate);
propertyBlock.SetColor("_RimColor", updateInfo.rimColor);
propertyBlock.SetFloat("_RimStep", updateInfo.rimStep);
propertyBlock.SetFloat("_RimFeather", updateInfo.rimFeather);
propertyBlock.SetFloat("_RimSpecRate", updateInfo.rimSpecRate);
propertyBlock.SetFloat("_RimHorizonOffset", updateInfo.RimHorizonOffset);
propertyBlock.SetFloat("_RimVerticalOffset", updateInfo.RimVerticalOffset);
propertyBlock.SetFloat("_RimHorizonOffset2", updateInfo.RimHorizonOffset2);
propertyBlock.SetFloat("_RimVerticalOffset2", updateInfo.RimVerticalOffset2);
propertyBlock.SetColor("_RimColor2", updateInfo.rimColor2);
propertyBlock.SetFloat("_RimStep2", updateInfo.rimStep2);
propertyBlock.SetFloat("_RimFeather2", updateInfo.rimFeather2);
propertyBlock.SetFloat("_RimSpecRate2", updateInfo.rimSpecRate2);
propertyBlock.SetFloat("_RimShadowRate2", updateInfo.globalRimShadowRate2);
propertyBlock.SetFloat("_RimShadowRate", updateInfo.globalRimShadowRate);
propertyBlock.SetColor("_RimColor", updateInfo.rimColor);
propertyBlock.SetFloat("_RimStep", updateInfo.rimStep);
propertyBlock.SetFloat("_RimFeather", updateInfo.rimFeather);
propertyBlock.SetFloat("_RimSpecRate", updateInfo.rimSpecRate);
propertyBlock.SetFloat("_RimHorizonOffset", updateInfo.RimHorizonOffset);
propertyBlock.SetFloat("_RimVerticalOffset", updateInfo.RimVerticalOffset);
propertyBlock.SetFloat("_RimHorizonOffset2", updateInfo.RimHorizonOffset2);
propertyBlock.SetFloat("_RimVerticalOffset2", updateInfo.RimVerticalOffset2);
propertyBlock.SetColor("_RimColor2", updateInfo.rimColor2);
propertyBlock.SetFloat("_RimStep2", updateInfo.rimStep2);
propertyBlock.SetFloat("_RimFeather2", updateInfo.rimFeather2);
propertyBlock.SetFloat("_RimSpecRate2", updateInfo.rimSpecRate2);
propertyBlock.SetFloat("_RimShadowRate2", updateInfo.globalRimShadowRate2);
propertyBlock.SetFloat("_UseOriginalDirectionalLight", 1f);
propertyBlock.SetVector("_OriginalDirectionalLightDir", tmpPos);
renderer.SetPropertyBlock(propertyBlock);
@@ -436,11 +439,11 @@ namespace Gallop.Live
foreach (var renderer in container.Renderers)
{
renderer.GetPropertyBlock(propertyBlock);
propertyBlock.SetColor("_CharaColor", updateInfo.color * updateInfo.colorPower);
propertyBlock.SetColor("_ToonDarkColor", updateInfo.toonDarkColor);
propertyBlock.SetColor("_ToonBrightColor", updateInfo.toonBrightColor);
propertyBlock.SetColor("_OutlineColor", updateInfo.outlineColor);
propertyBlock.SetFloat("_Saturation", updateInfo.Saturation);
propertyBlock.SetColor("_CharaColor", updateInfo.color * updateInfo.colorPower);
propertyBlock.SetColor("_ToonDarkColor", updateInfo.toonDarkColor);
propertyBlock.SetColor("_ToonBrightColor", updateInfo.toonBrightColor);
propertyBlock.SetColor("_OutlineColor", updateInfo.outlineColor);
propertyBlock.SetFloat("_Saturation", updateInfo.Saturation);
renderer.SetPropertyBlock(propertyBlock);
}
}
@@ -527,6 +530,7 @@ namespace Gallop.Live
_stageController != null ? _stageController.transform : null,
flareSetting != null ? flareSetting.lightStandard : 3f,
flareSetting != null ? flareSetting.underLimit : 0f);
_livePropsController.RegisterStageLighting(_stageController, _stageFlares);
foreach (var sheet in _liveTimelineControl.data.worksheetList)
{
if (sheet.bgColor1List != null)
@@ -573,7 +577,7 @@ namespace Gallop.Live
}
UpdateMainCamera();
};
}
public void InitializeCamera()
@@ -595,6 +599,21 @@ namespace Gallop.Live
_cameraTransforms[i] = camera.transform;
}
}
if (_cameraImageEffects == null)
{
_cameraImageEffects = new GallopImageEffect[_cameraObjects.Length];
for (int i = 0; i < _cameraObjects.Length; ++i)
{
var camera = _cameraObjects[i];
if (camera == null) continue;
var effect = camera.GetComponent<GallopImageEffect>();
if (effect == null) effect = camera.gameObject.AddComponent<LiveImageEffect>();
// Actual Director.InitializeCamera dispatches Initialize slot5
// before author enable/bloom state; do not rely on Awake.
effect.InitializeVolume();
_cameraImageEffects[i] = effect;
}
}
}
public void InitializeMultiCamera(LiveTimelineControl control)
@@ -780,6 +799,7 @@ namespace Gallop.Live
parameter.SunShafts = _volumeLightController.SunShafts;
parameter.LightShafts = _volumeLightController.LightShafts;
}
UpdateDofMaxFocalSize();
_lateTimelineAppliedThisFrame = true;
}
@@ -799,7 +819,7 @@ namespace Gallop.Live
if (_syncTime == false)
{
if(liveMusic.sourceList.Count == 0)
if (liveMusic.sourceList.Count == 0)
{
_syncTime = true;
}
@@ -899,7 +919,7 @@ namespace Gallop.Live
{
ApplyTimelineLateUpdate();
}
if (_enableMirrorReflection && _mirrorRenderInLateUpdate)
{
UpdateMirrorReflections();
@@ -998,7 +1018,7 @@ namespace Gallop.Live
public static List<UmaDatabaseEntry> GetLiveAllVoiceEntry(int songid, List<LiveCharacterLoadData> characters)
{
List<UmaDatabaseEntry> entryList = new List <UmaDatabaseEntry>();
List<UmaDatabaseEntry> entryList = new List<UmaDatabaseEntry>();
for (int i = 0; i < characters.Count; i++)
{
if (characters[i].CharaEntry.Name != "")
@@ -1138,10 +1158,11 @@ namespace Gallop.Live
}
private void InitializeMirrorReflections()
{
_stageController?.DestroyMirrorReflections();
_mirrorReflections.Clear();
if (!_enableMirrorReflection)
return;
_mirrorReflections.Clear();
AddMirrorReflections(_mirrorReflections, GetComponentsInChildren<MirrorReflection>(true));
@@ -1164,13 +1185,20 @@ namespace Gallop.Live
if (mainCam == null)
mainCam = Camera.main;
for (int i = 0; i < _mirrorReflections.Count; i++)
if (_stageController != null)
{
var mirror = _mirrorReflections[i];
if (mirror == null) continue;
mirror.Initialize(mainCam, i, false);
mirror.SetupBaseCamera(mainCam, GetMainCameraFovFactor);
_stageController.InitializeMirrorReflections(_mirrorReflections, mainCam,
GetMainCameraFovFactor, _liveTimelineControl, CharaContainerScript);
}
else
{
for (int i = 0; i < _mirrorReflections.Count; i++)
{
var mirror = _mirrorReflections[i];
if (mirror == null) continue;
mirror.Initialize(mainCam, i, false);
mirror.SetupBaseCamera(mainCam, GetMainCameraFovFactor);
}
}
Debug.Log($"[Mirror] Initialized {_mirrorReflections.Count} mirrors.");
@@ -1198,6 +1226,7 @@ namespace Gallop.Live
private void UpdateMirrorReflections()
{
_stageController?.PrepareMirrorCharacters();
if (_mirrorReflections == null || _mirrorReflections.Count == 0)
return;
@@ -1245,14 +1274,39 @@ namespace Gallop.Live
{
_mainGallopImageEffect =
mainCamera.gameObject
.AddComponent<GallopImageEffect>();
.AddComponent<LiveImageEffect>();
}
return _mainGallopImageEffect;
}
private string _lastDofBypassReason;
private void OnUpdatePostEffect_Dof(LiveTimelineKeyPostEffectDOFData key)
private float GetMaxForcalSize()
{
// Actual game RVA 0x71439d0 / AlterLateUpdate 0x713ec50.
// 0x0da24260 is the native 1e-30 fallback; never accumulate sampled sizes.
var data = _liveTimelineControl != null ? _liveTimelineControl.data : null;
return Mathf.Max(1e-30f, data != null ? data.maxForcalSize : 0f);
}
private void UpdateDofMaxFocalSize()
{
float maximum = GetMaxForcalSize();
if (_cameraImageEffects != null)
for (int i = 0; i < _cameraImageEffects.Length; ++i)
if (_cameraImageEffects[i] != null)
{
_cameraImageEffects[i].DofDiffusionBloomOverlayParam.DofMaxFocalSize = maximum;
_cameraImageEffects[i].RenderParameter.DofDiffuionBloomOverlay.DofMaxFocalSize = maximum;
}
if (_multiCameras != null)
for (int i = 0; i < _multiCameras.Length; ++i)
if (_multiCameras[i] != null)
_multiCameras[i].PostEffectParameter.DofDiffuionBloomOverlay.DofMaxFocalSize = maximum;
GetActivePostEffect()?.ApplyBloomParameter();
}
private void OnUpdatePostEffect_Dof(LiveTimelineKeyPostEffectDOFData key, Vector3? worldFocus)
{
var effect = GetActivePostEffect();
if (effect == null) return;
@@ -1271,60 +1325,28 @@ namespace Gallop.Live
bypassReason = "no render camera available for DOF evaluation";
if (key != null && bypassReason == null)
{
// master5's screenshot-tested inference; official flag names remain unknown.
// Actual game SetupDOFUpdateInfo RVA 0x726a610: bit18 enables DOF;
// bit16 selects camera look-at, bit17 a metric focal point.
bool metric = ((int)key.attribute & (1 << 17)) != 0;
bool cameraTarget = ((int)key.attribute & (1 << 16)) != 0;
Vector3 focus = Vector3.zero;
bool valid = metric;
if (!metric && cameraTarget)
{
valid = _liveTimelineControl.HasDofCameraLookAt &&
_liveTimelineControl.DofLookAtCamera == renderCamera;
focus = _liveTimelineControl.DofCameraLookAt;
}
else if (!metric)
{
int count = 0;
var locators = _liveTimelineControl.liveCharactorLocators;
for (int i = 0; i < locators.Length && i < 18; ++i)
if ((key.charactor & (1 << i)) != 0 && locators[i] != null)
{ focus += locators[i].liveCharaHeadPosition; ++count; }
valid = count > 0;
if (valid) focus /= count;
}
// Validate before the backend normalizes depth. In particular, do
// not clamp a behind-camera target to zero and render a full-frame blur.
// [REPORT §10.3-B3/§4.4] 原生 PrepareDofParam 只做 focal01<0→0 的下限夹紧
// (§4.4:只夹下限,无 Clamp01、无 farClipPlane 上限判定)。master7 曾把
// metric 焦距再减 nearClipPlane 且要求 focusDepth<farClipPlane,使
// 0<d<near 的近距焦点与超远焦点被二次关闭 DOF。对齐后只要求焦点在相机
// 前方(>0);相机背后目标仍按下述原注释保持关闭(不还原 focal01=0 全屏模糊)。
Vector3 focus = worldFocus.GetValueOrDefault();
bool valid = metric || worldFocus.HasValue;
// Native PrepareDofParam clamps normalized negative depth, not the
// authored focal point. Missing targets remain a DOF-only bypass.
float focusDepth = metric ? key.dofFocalPoint
: renderCamera.WorldToViewportPoint(focus).z;
valid = valid && !float.IsNaN(focusDepth) && !float.IsInfinity(focusDepth) &&
focusDepth > 0.0001f;
valid = valid && !float.IsNaN(focusDepth) && !float.IsInfinity(focusDepth);
if (!valid) bypassReason = "missing or invalid focus depth";
param.IsEnableDof = valid;
param.DofFocalPosition = focus;
param.DofFocalTransfrom = null;
// [REPORT §10.3-B4/§4.4] 原生 PrepareDofParam(RVA 0x1a20030) 不钳制
// DofFocalPoint 本身,只在后端对归一化 focalDistance01<0 夹 0
// (DofDiffusionBloomOverlayPass.cs:433-434)。删除 master7 自加的
// Max(0.01f)——它把 0~0.01m 的合法近距焦点系统性抬高到 0.01m,
// 近距离特写 DOF 焦点被推远;setter 无隐藏钳制(直接存值)。
param.DofFocalPoint = key.dofFocalPoint;
// Unlike master5's render Parameter, these source-property setters
// select Position/Transform/Point as a side effect. Restore the
// resolved mode LAST, or the default 1m point overwrites look-at
// and character focus before GallopImageEffect copies the state.
param.DofFocalType = metric ? DepthBlurAndBloom.DofFocalType.Point : DepthBlurAndBloom.DofFocalType.Position;
param.DofQualityType = key.dofQuality == 5 ? DepthBlurAndBloom.DofQuality.BackgroundAndForeground : DepthBlurAndBloom.DofQuality.OnlyBackground;
param.DofFocalSize = Mathf.Max(0f, key.forcalSize);
param.DofMaxFocalSize = Mathf.Max(param.DofMaxFocalSize, param.DofFocalSize);
param.DofMaxBlurSpread = Mathf.Max(0f, key.blurSpread);
param.DofForegroundSize = Mathf.Max(0f, key.dofForegroundSize);
param.DofSmoothness = Mathf.Max(0.1f, key.dofSmoothness);
param.DofBlurType = (DepthBlurAndBloom.DofBlur)Mathf.Clamp(key.dofBlurType, 0, 3);
param.IsEnableDof = valid && ((int)key.attribute & (1 << 18)) != 0;
// Source setters select the mode; write only the selected coordinate.
if (metric) param.DofFocalPoint = key.dofFocalPoint;
else param.DofFocalPosition = focus;
param.DofQualityType = (DepthBlurAndBloom.DofQuality)key.dofQuality;
param.DofFocalSize = key.forcalSize;
param.DofMaxFocalSize = GetMaxForcalSize();
param.DofMaxBlurSpread = key.blurSpread;
param.DofForegroundSize = key.dofForegroundSize;
param.DofSmoothness = key.dofSmoothness;
param.DofBlurType = (DepthBlurAndBloom.DofBlur)key.dofBlurType;
param.BallBlurPowerFactor = key.BallBlurPowerFactor;
param.BallBlurBrightnessThreshhold = key.BallBlurBrightnessThreshhold;
param.BallBlurBrightnessIntensity = key.BallBlurBrightnessIntensity;
@@ -1386,18 +1408,18 @@ namespace Gallop.Live
// Distance fog: apply via RenderSettings when isDistance is true.
// Either branch enables scene fog; both false disables it.
bool applyDistanceFog = key.isDistance && !key.isHeight;
bool applyHeightFog = key.isHeight;
bool applyHeightFog = key.isHeight;
RenderSettings.fog = applyDistanceFog || applyHeightFog;
RenderSettings.fog = applyDistanceFog || applyHeightFog;
RenderSettings.fogColor = key.color;
if (applyHeightFog)
{
RenderSettings.fogMode = FogMode.ExponentialSquared;
RenderSettings.fogMode = FogMode.ExponentialSquared;
RenderSettings.fogDensity = key.heightDensity;
// Forward height and fog length as globals so stage shaders can consume them.
float fogLength = Mathf.Max(0.001f, key.end - key.start);
Shader.SetGlobalFloat("_Global_FogHeight", key.height);
Shader.SetGlobalFloat("_Global_FogHeight", key.height);
Shader.SetGlobalFloat("_Global_FogHeightDensity", key.heightDensity);
Shader.SetGlobalVector("_Global_FogLength",
new Vector4(fogLength, fogLength, fogLength, fogLength));
@@ -1408,16 +1430,16 @@ namespace Gallop.Live
switch (key.fogMode)
{
case 1:
RenderSettings.fogMode = FogMode.Linear;
RenderSettings.fogMode = FogMode.Linear;
RenderSettings.fogStartDistance = key.start + key.startDistance;
RenderSettings.fogEndDistance = key.end;
RenderSettings.fogEndDistance = key.end;
break;
case 2:
RenderSettings.fogMode = FogMode.Exponential;
RenderSettings.fogMode = FogMode.Exponential;
RenderSettings.fogDensity = key.expDensity;
break;
default:
RenderSettings.fogMode = FogMode.ExponentialSquared;
RenderSettings.fogMode = FogMode.ExponentialSquared;
RenderSettings.fogDensity = key.expDensity;
break;
}
@@ -1439,7 +1461,7 @@ namespace Gallop.Live
private void OnUpdatePostEffect_BloomDiffusion(PostEffectUpdateInfo_BloomDiffusion updateInfo)
{
GallopImageEffect imageEffect = GetActivePostEffect();
if (imageEffect == null) return;
@@ -1483,9 +1505,9 @@ namespace Gallop.Live
updateInfo.diffusionContrast;
imageEffect.ApplyBloomParameter();
// Debug.Log(
// $"[BloomDirector] activeCameraIndex={_activeCameraIndex}, " +
// $"imageEffect={(imageEffect != null ? imageEffect.name : "null")}");
// Debug.Log(
// $"[BloomDirector] activeCameraIndex={_activeCameraIndex}, " +
// $"imageEffect={(imageEffect != null ? imageEffect.name : "null")}");
}
private void OnUpdateVolumeLight(LiveVolumeLightTimeline.VolumeUpdateInfo info)
{
@@ -1499,6 +1521,7 @@ namespace Gallop.Live
private void OnDestroy()
{
_stageController?.DestroyMirrorReflections();
UnbindTimelineEvents();
_footLightRuntime?.Dispose();
_footLightRuntime = null;
@@ -25,6 +25,9 @@ namespace Gallop.Live
private readonly List<RuntimeProp> instances = new List<RuntimeProp>();
private readonly HashSet<string> warnings = new HashSet<string>(StringComparer.Ordinal);
private bool disposed;
private StageController registeredStage;
private StageBlinkLightDriver registeredBlinkDriver;
private Gallop.RenderPipeline.RecoveredLensFlareController registeredFlares;
// Same predicate used by LiveEffectController. Gated tracks are not silently
// enabled when the Director has not supplied a variation selection.
@@ -72,6 +75,8 @@ namespace Gallop.Live
public bool DefaultPropParent;
public readonly Dictionary<string, Transform> Nodes = new Dictionary<string, Transform>(StringComparer.Ordinal);
public RendererState[] Renderers;
public Props[] StageProps;
public string NameSuffixToken;
public LiveTimelineKeyPropsData Appearance, NextAppearance;
public LiveTimelineKeyPropsAttachData Attachment, NextAttachment;
public float AppearanceRatio, AttachmentRatio;
@@ -139,8 +144,11 @@ namespace Gallop.Live
var instance = Object.Instantiate(prefab, anchor, false);
var runtime = new RuntimeProp
{
CharacterIndex = c, PropsId = id, Setting = setting,
Instance = instance, Anchor = anchor,
CharacterIndex = c,
PropsId = id,
Setting = setting,
Instance = instance,
Anchor = anchor,
Animator = instance.GetComponentInChildren<Animator>(true)
};
CacheNodes(runtime);
@@ -154,9 +162,42 @@ namespace Gallop.Live
{
ResolveDefaultAttachment(prop);
if (prop.DefaultTarget != null) ApplyAttachment(prop);
var character = characters[prop.CharacterIndex];
prop.StageProps = prop.Instance.GetComponentsInChildren<Props>(true);
prop.NameSuffixToken = "_" + prop.CharacterIndex.ToString(CultureInfo.InvariantCulture);
foreach (var component in prop.StageProps)
component.SetScale(character.HeadBone.transform, character.Position, character.BodyScale,
prop.Setting.isInfluenceOfCharaHeight);
// Animation transitions restore the initialized pose, not the prefab's
// unadjusted stand height. Native CreateProps scales once before playback.
CacheNodes(prop);
}
}
// Actual-game Director.CreateProps registers all three stage work arrays
// after creating/scaling props (Komoe RVA 0x7154755..0x71547ea).
internal void RegisterStageLighting(StageController stage,
Gallop.RenderPipeline.RecoveredLensFlareController flares)
{
if (stage == null) return;
registeredStage = stage;
registeredBlinkDriver = stage.GetComponent<StageBlinkLightDriver>();
registeredFlares = flares;
foreach (var prop in instances)
foreach (var component in prop.StageProps)
{
var transforms = component.StageObjectTransformArray;
if (transforms != null)
foreach (var node in transforms)
if (node != null) stage.RegisterObjectTransform(node, prop.NameSuffixToken);
flares?.AddSources(component.transform, prop.NameSuffixToken);
var roots = component.BlinkLightRootObjectArray;
if (roots != null && registeredBlinkDriver != null)
foreach (var root in roots)
if (root != null) registeredBlinkDriver.RegisterRoot(root, prop.NameSuffixToken, flares);
}
}
public static void CollectResourcePaths(LiveTimelinePropsSettings settings,
IList<UmaContainerCharacter> characters, ISet<string> output)
{
@@ -464,6 +505,7 @@ namespace Gallop.Live
ApplyAppearance(prop);
ApplyAttachment(prop);
}
registeredBlinkDriver?.UpdateRegisteredRoots();
}
private void DiagnoseRequestedResource(LiveTimelineKeyPropsData key)
@@ -691,6 +733,19 @@ namespace Gallop.Live
disposed = true;
foreach (var prop in instances)
{
foreach (var component in prop.StageProps)
{
if (component == null) continue;
var transforms = component.StageObjectTransformArray;
if (transforms != null && registeredStage != null)
foreach (var node in transforms)
if (node != null) registeredStage.UnregisterObjectTransform(node, prop.NameSuffixToken);
var roots = component.BlinkLightRootObjectArray;
if (roots != null && registeredBlinkDriver != null)
foreach (var root in roots)
if (root != null) registeredBlinkDriver.UnregisterRoot(root, prop.NameSuffixToken);
registeredFlares?.RemoveSources(component.transform, prop.NameSuffixToken);
}
if (prop.Graph.IsValid()) prop.Graph.Destroy();
// Destroy separately: a prop-to-prop parent may already have been removed.
if (prop.Instance != null) Object.Destroy(prop.Instance);
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
@@ -79,6 +80,8 @@ public class MirrorReflection : MonoBehaviour
private event Action<ScriptableRenderContext, Camera> _endCameraRenderingCallbacks;
private bool _isRenderingNow;
private readonly Stack<int> _mirrorObjectLayers = new Stack<int>(4);
internal Live.StageController LifecycleOwner { get; set; }
private readonly UniversalRenderPipeline.SingleCameraRequest _singleCameraRequest =
new UniversalRenderPipeline.SingleCameraRequest();
@@ -194,6 +197,8 @@ public class MirrorReflection : MonoBehaviour
private void OnDisable()
{
_isEnabled = false;
LifecycleOwner?.RestoreMirrorActorLayers(_mirrorCamera);
RestoreMirrorObjectLayers();
ClearMirrorMaterialBindingOnDisable();
}
@@ -222,6 +227,8 @@ public class MirrorReflection : MonoBehaviour
private void OnDestroy()
{
LifecycleOwner?.ReleaseMirrorReflection(this);
RestoreMirrorObjectLayers();
ReleaseMirrorTexture();
if (_mirrorCamera != null)
@@ -304,6 +311,9 @@ public class MirrorReflection : MonoBehaviour
private void TryAutoInitializeIfPossible()
{
// During live playback StageController is the sole initialization owner.
if (Live.Director.instance != null || GetComponentInParent<Live.StageController>() != null)
return;
EnsureSelfReferences();
if (!EnsureBaseCamera())
@@ -314,6 +324,8 @@ public class MirrorReflection : MonoBehaviour
public void Initialize(Camera baseCamera, int mirrorIndex = -1, bool isUseBaseCameraTextureSize = false)
{
LifecycleOwner?.PrepareMirrorReinitialization(this);
RestoreMirrorObjectLayers();
_isInitialized = false;
EnsureSelfReferences();
@@ -356,6 +368,7 @@ public class MirrorReflection : MonoBehaviour
UpdateMirrorParams();
_isInitialized = true;
LifecycleOwner?.CompleteMirrorReinitialization(this);
Log($"Initialize success. mirrorIndex={_mirrorIndex}, useBaseCameraTextureSize={_isUseBaseCameraTextureSize}");
}
@@ -430,13 +443,32 @@ public class MirrorReflection : MonoBehaviour
public void SetMirrorObjectLayer(int layer)
{
_objectLayer = layer;
gameObject.layer = layer;
if (!_isInitialized || layer < 0)
return;
_objectLayer = gameObject.layer;
_mirrorObjectLayers.Push(_objectLayer);
SetMirrorObjectLayerRecursively(transform, layer);
}
public void ResetMirrorObjectLayer()
{
_objectLayer = gameObject.layer;
if (_mirrorObjectLayers.Count == 0)
return;
_objectLayer = _mirrorObjectLayers.Pop();
SetMirrorObjectLayerRecursively(transform, _objectLayer);
}
internal void RestoreMirrorObjectLayers()
{
while (_mirrorObjectLayers.Count > 0)
ResetMirrorObjectLayer();
}
private static void SetMirrorObjectLayerRecursively(Transform root, int layer)
{
root.gameObject.layer = layer;
for (int i = 0; i < root.childCount; i++)
SetMirrorObjectLayerRecursively(root.GetChild(i), layer);
}
public void SetActive(bool active)
@@ -448,8 +480,11 @@ public class MirrorReflection : MonoBehaviour
public void SetLightMirrorShader(bool isEnable)
{
// �ٷ����������Լҵ� _mirrorCameraData ��д���ء�
// �����ڲ��ùٷ����� RenderPipeline���������ﱣ�ֿ�ʵ�����ӿڼ��ݡ�
// Native RVA 0x19b7f90 writes CameraData.MirrorCasterQuality (0/1).
// GallopRenderer replaces both forward queues with SimpleMirrorCaster
// when quality is 1; renderer slot 1 is installed by LiveRenderSetup.
if (_mirrorCamera != null)
_mirrorCamera.GetUniversalAdditionalCameraData().SetRenderer(isEnable ? 1 : -1);
}
public void SetMirrorVisibleOfficialStyle(bool visible, bool pauseRenderWhenHidden = true)
@@ -911,6 +946,8 @@ public class MirrorReflection : MonoBehaviour
return;
_isRenderingNow = true;
bool oldInvert = GL.invertCulling;
int receiverLayerDepth = _mirrorObjectLayers.Count;
try
{
UpdateRenderTexture();
@@ -924,25 +961,9 @@ public class MirrorReflection : MonoBehaviour
OnPreDraw?.Invoke(this);
_beginCameraRenderingCallbacks?.Invoke(default, _mirrorCamera);
bool oldInvert = GL.invertCulling;
try
{
GL.invertCulling = !oldInvert;
if (!TrySubmitSingleCameraRequest())
_mirrorCamera.Render();
}
finally
{
GL.invertCulling = oldInvert;
if (_mirrorCamera != null)
{
_mirrorCamera.ResetWorldToCameraMatrix();
_mirrorCamera.ResetProjectionMatrix();
_mirrorCamera.ResetCullingMatrix();
}
}
GL.invertCulling = !oldInvert;
if (!TrySubmitSingleCameraRequest())
_mirrorCamera.Render();
}
catch (Exception e)
{
@@ -950,9 +971,57 @@ public class MirrorReflection : MonoBehaviour
}
finally
{
OnPostDraw?.Invoke(this);
_endCameraRenderingCallbacks?.Invoke(default, _mirrorCamera);
_isRenderingNow = false;
try
{
GL.invertCulling = oldInvert;
if (_mirrorCamera != null)
{
_mirrorCamera.ResetWorldToCameraMatrix();
_mirrorCamera.ResetProjectionMatrix();
_mirrorCamera.ResetCullingMatrix();
}
}
finally
{
try
{
OnPostDraw?.Invoke(this);
}
finally
{
try
{
_endCameraRenderingCallbacks?.Invoke(default, _mirrorCamera);
}
finally
{
try
{
LifecycleOwner?.RestoreMirrorActorLayers(_mirrorCamera);
}
finally
{
try
{
// Preserve a parent ordinary-camera scope during a nested mirror draw.
while (_mirrorObjectLayers.Count > receiverLayerDepth)
ResetMirrorObjectLayer();
}
finally
{
try
{
GL.invertCulling = oldInvert;
}
finally
{
_isRenderingNow = false;
}
}
}
}
}
}
}
}
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
@@ -269,12 +269,16 @@ namespace Gallop.Live
[SerializeField] private bool _lastLoadSucceeded;
[SerializeField] private int _lastSyncedStageInstanceId;
[SerializeField] private int _lastContextSlotHash;
private bool _hasResolvedContextSlots;
public int LoadedMusicId => _loadedMusicId;
public string LoadedRootPath => _loadedRootPath;
public bool HasTriedLoad => _hasTriedLoad;
public bool LastLoadSucceeded => _lastLoadSucceeded;
public int ContextSlotCount => contextSlots != null ? contextSlots.Count : 0;
// A loaded table may legitimately contain no UVMovie rows. Completion
// is independent of slot availability, so that case is not retried each frame.
public bool HasResolvedContextSlots => _hasResolvedContextSlots;
private void Start()
{
@@ -432,10 +436,12 @@ namespace Gallop.Live
_lastSyncedStageInstanceId = 0;
_lastContextSlotHash = 0;
_hasResolvedContextSlots = false;
}
public bool RebuildContextSlotsFromLiveSettings(LiveTimelineControl timelineControl, int musicId, bool force = false)
{
_hasResolvedContextSlots = false;
string csvText = ResolveLiveSettingsCsvText(musicId);
if (string.IsNullOrWhiteSpace(csvText))
{
@@ -447,6 +453,7 @@ namespace Gallop.Live
List<LiveSettingsUvMovieRow> sourceRows = ParseLiveSettingsUvMovieRows(csvText);
if (sourceRows.Count == 0)
{
_hasResolvedContextSlots = true;
if (verboseLog)
Debug.LogWarning("[MonitorUvMovieProvider] liveSettings csv contains no type=4 UVMovie rows.");
return false;
@@ -502,6 +509,7 @@ namespace Gallop.Live
int slotHash = ComputeSlotHash(resolvedSlots);
if (!force && _lastContextSlotHash == slotHash && contextSlots.Count == resolvedSlots.Count)
{
_hasResolvedContextSlots = true;
if (verboseLog)
Debug.Log($"[MonitorUvMovieProvider] liveSettings slots unchanged: total={resolvedSlots.Count}, musicId={musicId}");
return false;
@@ -510,6 +518,7 @@ namespace Gallop.Live
contextSlots = resolvedSlots;
_lastSyncedStageInstanceId = musicId;
_lastContextSlotHash = slotHash;
_hasResolvedContextSlots = true;
if (verboseLog)
{
@@ -168,7 +168,7 @@ namespace Gallop.Live
// updates these only on flagged keys; CopyFrom must not erase their state.
if (((int)positionKey.attribute & 0x20000) != 0)
{
_timelineCullingMask = GetMonitorCullingMask(positionKey.cullingLayer);
_timelineCullingMask = positionKey.GetCullingMask();
_hasTimelineCullingMask = true;
}
if (((int)positionKey.attribute & 0x40000) != 0)
@@ -241,24 +241,6 @@ namespace Gallop.Live
return _texture.IsCreated() || _texture.Create();
}
private static int GetMonitorCullingMask(LiveCameraCullingLayer layers)
{
// LiveCameraCullingLayer_Helper.GetCullingMask RVA 0x1af2220.
int mask = 0;
if ((layers & LiveCameraCullingLayer.TransparentFX) != 0) mask |= 1 << 1;
if ((layers & LiveCameraCullingLayer.Effect) != 0) mask |= 1 << 11;
if ((layers & LiveCameraCullingLayer.Background3d_NotReflect) != 0) mask |= 1 << 25;
if ((layers & LiveCameraCullingLayer.Background3d) != 0) mask |= 1 << 12;
if ((layers & LiveCameraCullingLayer.Character3d) != 0) mask |= 1 << 13;
if ((layers & LiveCameraCullingLayer.Character3d_0) != 0) mask |= 1 << 27;
if ((layers & LiveCameraCullingLayer.Character3d_1) != 0) mask |= 1 << 28;
if ((layers & LiveCameraCullingLayer.Character3d_NotReflect) != 0) mask |= 1 << 26;
if ((layers & LiveCameraCullingLayer.NotLayerDefault) == 0)
mask |= GraphicSettings.GetCullingLayer(GraphicSettings.LayerIndex.LayerDefault);
if ((layers & LiveCameraCullingLayer.NotLayer3d) == 0)
mask |= GraphicSettings.GetCullingLayer(GraphicSettings.LayerIndex.Layer3D);
return mask;
}
private static bool FindKeys<T>(ILiveTimelineKeyDataList keys, LiveTimelineControl timeline, float frame,
out T current, out T next) where T : LiveTimelineKey
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Reflection;
using Gallop.Live.Cutt;
@@ -31,7 +31,7 @@ namespace Gallop.Live
public string baseColorProperty = "_BaseColor";
public string monitorWidthProperty = "_MonitorWidth";
public string monitorHeightProperty = "_MonitorHeight";
public string crossFadeRateProperty = "_CrossFadeRate";
public string blendFactorProperty = "_BlendFactor";
public string srcBlendModeProperty = "_SrcBlendMode";
public string dstBlendModeProperty = "_DstBlendMode";
public string srcBlendProperty = "_SrcBlend";
@@ -45,6 +45,7 @@ namespace Gallop.Live
public Vector2 baseMainScale;
public Vector2 baseMainOffset;
public bool cameraAppliedThisFrame;
public bool cameraTextureBound;
public string rendererKey;
public string materialKey;
public string rendererCompact;
@@ -82,7 +83,7 @@ namespace Gallop.Live
public float alpha;
public Color colorFade;
public Color baseColor;
public float crossFadeRate;
public float blendFactor;
public float filterTexScale;
public int srcBlendMode;
public int dstBlendMode;
@@ -312,10 +313,11 @@ namespace Gallop.Live
_lastPreparedMusicId = musicId;
bool synced = false;
if (!_providerContextReady || stageChanged || _provider.ContextSlotCount == 0)
if (!_providerContextReady || stageChanged ||
(_provider.ContextSlotCount == 0 && !_provider.HasResolvedContextSlots))
{
synced = _provider.RebuildContextSlotsFromLiveSettings(_ctl, musicId, force: stageChanged || musicChanged);
_providerContextReady = synced || _provider.ContextSlotCount > 0;
_providerContextReady = synced || _provider.ContextSlotCount > 0 || _provider.HasResolvedContextSlots;
}
if (_stage != null)
@@ -685,14 +687,14 @@ namespace Gallop.Live
if (assignMaskTextureToFilterTex && state.hasMainTexture)
state.filterTexture = state.main.maskTexture;
// 保持 _Alpha 为材质原本的值
// 时间轴的监视器数据没有提供专用的透明度字段;
// colorFade 和 BaseColor 会分别传递给对应的着色器参数
state.alpha = 0f;
// Native UpdateMonitor (0x1a93a70) applies these even when neither
// movie slot resolves. An empty slot is not an absent control key:
// ColorFade=(0,0,0,0) must still turn the authored white screen black.
state.alpha = crossFadeRate;
state.colorFade = colorFade;
state.useBaseColor = !IsColorEffectivelyClear(baseColor);
state.baseColor = state.useBaseColor ? baseColor : Color.white;
state.crossFadeRate = crossFadeRate;
state.blendFactor = blendFactor;
state.filterTexScale = filterTexScale;
state.srcBlendMode = curKey.SrcBlendMode;
state.dstBlendMode = curKey.DstBlendMode;
@@ -700,7 +702,7 @@ namespace Gallop.Live
state.renderQueue = curKey.RenderQueueNo;
state.hasRenderQueue = curKey.IsRenderQueue != 0;
return state.hasMainTexture;
return true;
}
private MonitorUvMovieContextSlot ResolvePrimarySlot(
@@ -1043,7 +1045,7 @@ namespace Gallop.Live
for (int i = 0; i < _bindings.Count; i++)
{
MonitorMaterialBinding binding = _bindings[i];
if (!binding.hasAppliedState || !binding.appliedState.useMonitorCamera ||
if (!binding.cameraTextureBound ||
(!force && binding.cameraAppliedThisFrame))
continue;
Material material = binding.material;
@@ -1056,6 +1058,7 @@ namespace Gallop.Live
if (binding.hasUvAdjust)
material.SetVector("_UVAdjust", binding.baseUvAdjust);
}
binding.cameraTextureBound = false;
binding.hasAppliedState = false;
}
}
@@ -1066,7 +1069,11 @@ namespace Gallop.Live
if (material == null)
return;
binding.cameraAppliedThisFrame = state.useMonitorCamera;
// An empty movie slot leaves the current texture untouched, as native
// UpdateMonitorInMovie does. Keep ownership until a real replacement
// arrives, so disabling/rebinding still detaches the capture RT.
binding.cameraAppliedThisFrame = state.useMonitorCamera ||
(!state.hasMainTexture && binding.cameraTextureBound);
if (state.hasMainTexture && HasTextureProperty(material, mainTexProperty))
{
@@ -1079,6 +1086,7 @@ namespace Gallop.Live
material.SetTextureScale(mainTexProperty, state.main.scale);
material.SetTextureOffset(mainTexProperty, state.main.offset);
}
binding.cameraTextureBound = state.useMonitorCamera;
}
if (HasTextureProperty(material, fadeTexProperty))
@@ -1124,7 +1132,11 @@ namespace Gallop.Live
}
}
float appliedAlpha = state.useMonitorCamera ? 0f : binding.baseAlpha;
// Native movie mode maps CrossFadeRate to _Alpha; capture mode does
// not overwrite it. Retain the last value across capture transitions.
float appliedAlpha = state.useMonitorCamera
? (binding.hasAppliedState ? binding.appliedState.alpha : binding.baseAlpha)
: state.alpha;
Color appliedColorFade = state.colorFade;
Color appliedBaseColor = state.useBaseColor ? state.baseColor : binding.baseColor;
@@ -1161,8 +1173,8 @@ namespace Gallop.Live
}
material.SetVector("_UVAdjust", uvAdjust);
}
if (!binding.hasAppliedState || !Approximately(binding.appliedState.crossFadeRate, state.crossFadeRate))
TrySetFloat(material, crossFadeRateProperty, state.crossFadeRate);
if (!binding.hasAppliedState || !Approximately(binding.appliedState.blendFactor, state.blendFactor))
TrySetFloat(material, blendFactorProperty, state.blendFactor);
if (applyBlendModeProperties)
{
@@ -192,6 +192,8 @@ namespace Gallop.Live
RenderCamera.nearClipPlane = current.nearClip;
RenderCamera.farClipPlane = current.farClip;
RenderCamera.fieldOfView = Mathf.LerpUnclamped(current.fov, next.fov, t);
if (((int)current.attribute & 0x40000) != 0)
RenderCamera.backgroundColor = current.BgColor;
}
if (current.maskType == LiveTimelineKeyMultiCameraPositionData.MaskType.Single && transitioning)
{
@@ -0,0 +1,50 @@
using System;
using UnityEngine;
namespace Gallop.Live
{
// Serialized contract from common prop000/001 TypeTrees (assembly: umamusume).
// Height adjustment follows the actual game Props.SetScale (Komoe RVA 0x71daed0).
public sealed class Props : MonoBehaviour
{
[Serializable]
public sealed class AdjustmentData
{
public Transform Transform;
public Vector3 OffsetRange;
public Vector3 TransformRate;
public int TargetNode;
public Vector3 TargetOffset;
public Vector3 TargetPosition { get; internal set; }
}
[SerializeField] private AdjustmentData[] _adjustmentDataArray;
[SerializeField] private bool _isInfluenceOfCharaHeight;
[SerializeField] private GameObject[] _blinkLightRootObjectArray;
[SerializeField] private Transform[] _stageObjectTransformArray;
internal GameObject[] BlinkLightRootObjectArray => _blinkLightRootObjectArray;
internal Transform[] StageObjectTransformArray => _stageObjectTransformArray;
internal void SetScale(Transform headTransform, Transform positionNode, float bodyScale,
bool isInfluenceOfCharaHeight)
{
_isInfluenceOfCharaHeight = isInfluenceOfCharaHeight;
if (_adjustmentDataArray == null || _adjustmentDataArray.Length == 0) return;
// Native Head target: world-space Y difference only. Neither the authored
// local position nor head X/Z participates, and the result is not clamped.
Vector3 targetPosition = new Vector3(0f, headTransform.position.y - positionNode.position.y, 0f);
for (int i = 0; i < _adjustmentDataArray.Length; i++)
{
var adjustment = _adjustmentDataArray[i];
if (adjustment.Transform == null) continue;
adjustment.TargetPosition = targetPosition;
Vector3 position = _isInfluenceOfCharaHeight ? targetPosition / bodyScale : targetPosition;
adjustment.Transform.localPosition = Vector3.Scale(
position + adjustment.TargetOffset - adjustment.OffsetRange, adjustment.TransformRate);
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8ba55f9f4016407da01e39622a086b67
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
@@ -106,11 +106,11 @@ namespace Gallop.Live
public float powerDiff;
public int loopCountMax;
public float waitTime;
public float waitTime;
public float turnOnTime;
public float turnOffTime;
public float keepTime;
public float intervalTime;
public float intervalTime;
public float loopTime;
public float currentPower;
@@ -161,6 +161,10 @@ namespace Gallop.Live
private readonly Dictionary<string, RootCache> _rootCache = new Dictionary<string, RootCache>(256);
private readonly Dictionary<string, BlinkRootRuntime> _runtime = new Dictionary<string, BlinkRootRuntime>(256);
private readonly Dictionary<string, List<RootCache>> _registeredRoots =
new Dictionary<string, List<RootCache>>(StringComparer.Ordinal);
private Gallop.RenderPipeline.RecoveredLensFlareController _registeredFlares;
private int _registeredUpdateFrame = -1;
private enum IndexMode
{
@@ -200,6 +204,7 @@ namespace Gallop.Live
public bool wantsMpb;
// 官方 RendererData 层
public Gallop.RenderPipeline.CustomLensFlare customLensFlare;
public WashLightController washLightController;
public UnityLensFlareController unityLensFlareController;
public Material material;
@@ -225,6 +230,16 @@ namespace Gallop.Live
private static readonly Regex ReSuffixNumber = new Regex(@"_(\d+)$", RegexOptions.Compiled);
private static readonly Regex ReLastDigits = new Regex(@"(\d+)(?!.*\d)", RegexOptions.Compiled);
private readonly List<Material> _sharedMaterialScratch = new List<Material>(4);
private readonly List<Material> _blendMaterialScratch = new List<Material>(4);
private struct BlendMaterialClassification
{
public Shader shader;
public bool isTarget;
}
private readonly Dictionary<Material, BlendMaterialClassification> _blendMaterialClassification =
new Dictionary<Material, BlendMaterialClassification>();
private void Awake()
{
@@ -238,6 +253,8 @@ namespace Gallop.Live
private void OnDisable()
{
_blendMaterialScratch.Clear();
_blendMaterialClassification.Clear();
Unbind();
}
@@ -275,9 +292,60 @@ namespace Gallop.Live
_groundChosen.Clear();
}
private static bool IsBlinkRootName(string name)
internal void RegisterRoot(GameObject root, string nameSuffixToken,
Gallop.RenderPipeline.RecoveredLensFlareController flares)
{
string name = root.name.Replace("(Clone)", string.Empty) + nameSuffixToken;
_registeredFlares = flares;
if (!_registeredRoots.TryGetValue(name, out var roots))
{
roots = new List<RootCache>();
_registeredRoots.Add(name, roots);
}
string runtimeKey = name + "__U" + root.GetInstanceID();
var cache = GetOrBuildRootCache(runtimeKey, root);
roots.Add(cache);
ApplyRootOffCached(runtimeKey, root);
}
internal void UpdateRegisteredRoots()
{
foreach (var entry in _registeredRoots)
{
if (!_latest.TryGetValue(entry.Key, out var item)) continue;
var info = item.updateInfo;
info.progressTime = Mathf.Max(0f, info.progressTime) * Mathf.Max(0.0001f, localTimeScale);
foreach (var root in entry.Value)
if (root.rootGo != null)
ApplyToRootCached(root.rootName, root.rootGo, info, item.currentLiveTime);
}
_registeredUpdateFrame = Time.frameCount;
}
internal void UnregisterRoot(GameObject root, string nameSuffixToken)
{
string name = root.name.Replace("(Clone)", string.Empty) + nameSuffixToken;
if (!_registeredRoots.TryGetValue(name, out var roots)) return;
for (int i = roots.Count - 1; i >= 0; i--)
{
var cache = roots[i];
if (cache.rootGo != root) continue;
_rootCache.Remove(cache.rootName);
_runtime.Remove(cache.rootName);
_rootBase.Remove(cache.rootName);
roots.RemoveAt(i);
}
if (roots.Count == 0)
{
_registeredRoots.Remove(name);
_latest.Remove(name);
}
}
private bool IsBlinkRootName(string name)
{
if (string.IsNullOrEmpty(name)) return false;
if (_registeredRoots.ContainsKey(NormalizeRuntimeRootName(name))) return true;
if (name.IndexOf("_spotlight3d_controller", StringComparison.OrdinalIgnoreCase) >= 0) return false;
if (name.IndexOf("ledlight", StringComparison.OrdinalIgnoreCase) >= 0) return false;
@@ -435,7 +503,7 @@ namespace Gallop.Live
return false;
}
private void OnBlinkLight(LiveTimelineBlinkLightData data,ref BlinkLightUpdateInfo info,float currentLiveTime)
private void OnBlinkLight(LiveTimelineBlinkLightData data, ref BlinkLightUpdateInfo info, float currentLiveTime)
{
string rootName = (data != null) ? data.name : null;
if (string.IsNullOrEmpty(rootName)) return;
@@ -525,26 +593,37 @@ namespace Gallop.Live
float liveNow = item.currentLiveTime;
if (_stage.StageObjectUnitMap.TryGetValue(rootName, out var unit) &&
unit != null && unit.ChildObjects != null && unit.ChildObjects.Length > 0)
if (_registeredRoots.TryGetValue(rootName, out var registeredRoots))
{
for (int i = 0; i < unit.ChildObjects.Length; i++)
if (_registeredUpdateFrame == Time.frameCount) continue;
for (int i = 0; i < registeredRoots.Count; i++)
{
var childPrefab = unit.ChildObjects[i];
if (childPrefab == null)
continue;
if (_stage.StageObjectMap.TryGetValue(childPrefab.name, out var realGo) && realGo != null)
{
string runtimeKey = rootName + "__U" + i;
ApplyToRootCached(runtimeKey, realGo, updateInfo, liveNow);
}
var root = registeredRoots[i];
if (root.rootGo != null)
ApplyToRootCached(root.rootName, root.rootGo, updateInfo, liveNow);
}
}
else if (_stage.StageObjectMap.TryGetValue(rootName, out var rootGo) && rootGo != null)
{
ApplyToRootCached(rootName, rootGo, updateInfo, liveNow);
}
else
if (_stage.StageObjectUnitMap.TryGetValue(rootName, out var unit) &&
unit != null && unit.ChildObjects != null && unit.ChildObjects.Length > 0)
{
for (int i = 0; i < unit.ChildObjects.Length; i++)
{
var childPrefab = unit.ChildObjects[i];
if (childPrefab == null)
continue;
if (_stage.StageObjectMap.TryGetValue(childPrefab.name, out var realGo) && realGo != null)
{
string runtimeKey = rootName + "__U" + i;
ApplyToRootCached(runtimeKey, realGo, updateInfo, liveNow);
}
}
}
else if (_stage.StageObjectMap.TryGetValue(rootName, out var rootGo) && rootGo != null)
{
ApplyToRootCached(rootName, rootGo, updateInfo, liveNow);
}
}
// Exclusivity must be enforced AFTER the cached timeline update:
@@ -639,6 +718,7 @@ namespace Gallop.Live
var wash = go.GetComponent<WashLightController>();
var flare = go.GetComponent<UnityLensFlareController>();
var customFlare = go.GetComponent<Gallop.RenderPipeline.CustomLensFlare>();
var runtimeMat = r.material;
var mats = r.sharedMaterials;
pendingRenderers.Add(new RendererEntry
@@ -659,6 +739,7 @@ namespace Gallop.Live
washLightController = wash,
unityLensFlareController = flare,
customLensFlare = customFlare,
material = runtimeMat,
isWashLight = false,
isWashLightProjection = false,
@@ -866,7 +947,7 @@ namespace Gallop.Live
return b;
}
private void ApplyToRootCached(string runtimeKey,GameObject rootGo,BlinkLightUpdateInfo updateInfo,float liveNow)
private void ApplyToRootCached(string runtimeKey, GameObject rootGo, BlinkLightUpdateInfo updateInfo, float liveNow)
{
var rc = GetOrBuildRootCache(runtimeKey, rootGo);
if (rc.slotCount <= 0) return;
@@ -970,6 +1051,10 @@ namespace Gallop.Live
}
Color currentColor = new Color(slotColor.x, slotColor.y, slotColor.z, 1f);
// Native Blink.Update writes its power-weighted current color directly
// to the flare, with shader-color reading disabled (Komoe 0x7192856).
if (e.customLensFlare != null)
_registeredFlares?.SetBlinkColor(e.customLensFlare, currentColor * p);
int uvBias = (rc.rootIsUv || e.isUvAlphaMask) ? uvSortingBias : 0;
r.sortingOrder = baseOrder + uvBias + e.stableSlot * stride;
@@ -1281,6 +1366,8 @@ namespace Gallop.Live
{
var e = rc.renderers[i];
var r = e.r;
if (e.customLensFlare != null)
_registeredFlares?.SetBlinkColor(e.customLensFlare, Color.black);
if (r == null)
{
rc.dirty = true;
@@ -1288,7 +1375,7 @@ namespace Gallop.Live
}
EnsureLightBlinkBlendState(r, ref e,(int)fallbackLightBlendMode);
EnsureLightBlinkBlendState(r, ref e, (int)fallbackLightBlendMode);
if (e.wantsMpb)
{
@@ -1336,7 +1423,18 @@ namespace Gallop.Live
{
if (m == null) return false;
string sn = (m.shader != null) ? (m.shader.name ?? "") : "";
Shader shader = m.shader;
if (_blendMaterialClassification.TryGetValue(m, out var cached) && cached.shader == shader)
return cached.isTarget;
bool isTarget = ClassifyBlinkBlendMaterial(m, shader);
_blendMaterialClassification[m] = new BlendMaterialClassification { shader = shader, isTarget = isTarget };
return isTarget;
}
private static bool ClassifyBlinkBlendMaterial(Material m, Shader shader)
{
string sn = shader != null ? (shader.name ?? "") : "";
if (sn.IndexOf("LightBlinkBlend", StringComparison.OrdinalIgnoreCase) >= 0)
return true;
@@ -1401,19 +1499,17 @@ namespace Gallop.Live
int modeId = (int)mode;
// 不要再提前 return。
// 官方 Update 末尾每帧都会 TrySetLightBlendModeMaterialProperty。
// 你这里如果 cache return,材质被 timeline / prefab / 其他脚本改回 One/One 后就不会再修。
// if (e.blendConfigured && e.blendConfiguredMode == modeId)
// return;
// Preserve the native per-frame blend override, including recovery
// after another controller changes the material's blend properties.
var mats = r.materials;
if (mats == null || mats.Length == 0)
r.GetMaterials(_blendMaterialScratch);
var mats = _blendMaterialScratch;
if (mats.Count == 0)
return;
bool touched = false;
for (int i = 0; i < mats.Length; i++)
for (int i = 0; i < mats.Count; i++)
{
var m = mats[i];
if (!IsTargetBlinkBlendMaterial(m))
@@ -4,6 +4,7 @@ using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Rendering;
namespace Gallop.Live
{
@@ -131,7 +132,7 @@ namespace Gallop.Live
[Tooltip("レーザーマテリアル")]
private Material[] _laserMaterials;
private bool _laserSetupDone = false;
private LiveTimelineControl _laserSetupTimelineControl;
private readonly Dictionary<object, int> _laserDataIndexMap =
@@ -177,6 +178,237 @@ namespace Gallop.Live
private readonly Dictionary<int, MirrorReflection> _mirrorByTimelineHash = new Dictionary<int, MirrorReflection>();
private LiveTimelineControl _boundTimelineControl;
private const int MirrorCharacterSlotCount = 20;
private sealed class MirrorCameraTarget
{
internal MirrorReflection Mirror;
internal int BodyMask;
internal int HeadMask;
internal readonly Stack<Camera> ReceiverCameras = new Stack<Camera>(4);
}
private readonly List<MirrorCameraTarget> _mirrorCameraTargets = new List<MirrorCameraTarget>();
private readonly UmaContainerCharacter[] _mirrorBoundCharacters = new UmaContainerCharacter[MirrorCharacterSlotCount];
private IList<UmaContainerCharacter> _mirrorCharacters;
private LiveTimelineData _mirrorTimelineData;
private Camera _activeMirrorRenderingCamera;
private bool _mirrorRenderingCallbacksBound;
internal void InitializeMirrorReflections(IReadOnlyList<MirrorReflection> mirrors, Camera baseCamera,
Func<float> fovFactor, LiveTimelineControl timeline, IList<UmaContainerCharacter> characters)
{
DestroyMirrorReflections();
_mirrorTimelineData = timeline != null ? timeline.data : null;
_mirrorCharacters = characters;
_environmentMirrorTargets.Clear();
_mirrorByTimelineHash.Clear();
for (int i = 0; i < mirrors.Count; i++)
{
var mirror = mirrors[i];
if (mirror == null)
continue;
mirror.Initialize(baseCamera, i, false);
mirror.SetupBaseCamera(baseCamera, fovFactor);
mirror.LifecycleOwner = this;
// Native MirrorCameraTarget construction leaves both actor masks zero.
_mirrorCameraTargets.Add(new MirrorCameraTarget { Mirror = mirror });
RegisterMirrorReflection(mirror);
}
PrepareMirrorCharacters();
BindMirrorRenderingCallbacks();
}
internal void PrepareMirrorCharacters()
{
for (int i = 0; i < MirrorCharacterSlotCount; i++)
{
var character = _mirrorCharacters != null && i < _mirrorCharacters.Count ? _mirrorCharacters[i] : null;
if (_mirrorBoundCharacters[i] == character)
continue;
if (_mirrorBoundCharacters[i] != null)
_mirrorBoundCharacters[i].RestoreMirrorChangedLayers();
_mirrorBoundCharacters[i] = character;
if (character != null)
character.PrepareMirrorLayerCache();
}
}
private void BindMirrorRenderingCallbacks()
{
if (_mirrorRenderingCallbacksBound || !isActiveAndEnabled || _mirrorTimelineData == null ||
!_mirrorTimelineData.IsChangedCharaLayerOnlyMirrorRendering)
return;
_mirrorRenderingCallbacksBound = true;
for (int i = 0; i < _mirrorCameraTargets.Count; i++)
CompleteMirrorReinitialization(_mirrorCameraTargets[i].Mirror);
RenderPipelineManager.beginCameraRendering += OnBeginCameraRendering;
RenderPipelineManager.endCameraRendering += OnEndCameraRendering;
Camera.onPreCull += OnBeginBuiltInCameraRendering;
Camera.onPostRender += OnEndBuiltInCameraRendering;
}
private void UnbindMirrorRenderingCallbacks()
{
if (_mirrorRenderingCallbacksBound)
{
RenderPipelineManager.beginCameraRendering -= OnBeginCameraRendering;
RenderPipelineManager.endCameraRendering -= OnEndCameraRendering;
Camera.onPreCull -= OnBeginBuiltInCameraRendering;
Camera.onPostRender -= OnEndBuiltInCameraRendering;
_mirrorRenderingCallbacksBound = false;
}
for (int i = 0; i < _mirrorCameraTargets.Count; i++)
PrepareMirrorReinitialization(_mirrorCameraTargets[i].Mirror);
RestoreMirrorActorLayers();
}
internal void DestroyMirrorReflections()
{
UnbindMirrorRenderingCallbacks();
for (int i = 0; i < _mirrorCameraTargets.Count; i++)
if (_mirrorCameraTargets[i].Mirror != null)
_mirrorCameraTargets[i].Mirror.LifecycleOwner = null;
_mirrorCameraTargets.Clear();
_mirrorCharacters = null;
_mirrorTimelineData = null;
for (int i = 0; i < MirrorCharacterSlotCount; i++)
_mirrorBoundCharacters[i] = null;
}
internal void PrepareMirrorReinitialization(MirrorReflection mirror)
{
if (mirror == null)
return;
mirror.RemoveBeginCameraRenderingCallback(OnBeginMirrorCameraRendering);
mirror.RemoveEndCameraRenderingCallback(OnEndMirrorCameraRendering);
RestoreMirrorActorLayers(mirror.MirrorCamera);
mirror.RestoreMirrorObjectLayers();
var target = GetMirrorCameraTarget(mirror);
if (target != null)
{
target.BodyMask = 0;
target.HeadMask = 0;
target.ReceiverCameras.Clear();
}
}
internal void CompleteMirrorReinitialization(MirrorReflection mirror)
{
if (!_mirrorRenderingCallbacksBound || mirror == null || !mirror.IsInitialized)
return;
mirror.RemoveBeginCameraRenderingCallback(OnBeginMirrorCameraRendering);
mirror.RemoveEndCameraRenderingCallback(OnEndMirrorCameraRendering);
mirror.AddBeginCameraRenderingCallback(OnBeginMirrorCameraRendering);
mirror.AddEndCameraRenderingCallback(OnEndMirrorCameraRendering);
}
internal void ReleaseMirrorReflection(MirrorReflection mirror)
{
PrepareMirrorReinitialization(mirror);
for (int i = _mirrorCameraTargets.Count - 1; i >= 0; i--)
if (_mirrorCameraTargets[i].Mirror == mirror)
_mirrorCameraTargets.RemoveAt(i);
mirror.LifecycleOwner = null;
}
private MirrorCameraTarget GetMirrorCameraTarget(MirrorReflection mirror)
{
for (int i = 0; i < _mirrorCameraTargets.Count; i++)
if (_mirrorCameraTargets[i].Mirror == mirror)
return _mirrorCameraTargets[i];
return null;
}
private MirrorCameraTarget GetMirrorCameraTarget(Camera camera)
{
for (int i = 0; i < _mirrorCameraTargets.Count; i++)
{
var mirror = _mirrorCameraTargets[i].Mirror;
if (mirror != null && mirror.MirrorCamera == camera)
return _mirrorCameraTargets[i];
}
return null;
}
private void OnBeginMirrorCameraRendering(ScriptableRenderContext context, Camera camera)
{
var target = GetMirrorCameraTarget(camera);
if (target == null)
return;
RestoreMirrorActorLayers();
_activeMirrorRenderingCamera = camera;
int layer = GraphicSettings.GetLayer(GraphicSettings.LayerIndex.LayerCharacter3D_NotReflect);
for (int i = 0; i < MirrorCharacterSlotCount; i++)
if (_mirrorBoundCharacters[i] != null)
_mirrorBoundCharacters[i].SetLayerBeforeMirrorCameraRendering(
(target.BodyMask & (1 << i)) != 0, (target.HeadMask & (1 << i)) != 0, layer);
}
private void OnEndMirrorCameraRendering(ScriptableRenderContext context, Camera camera)
{
RestoreMirrorActorLayers(camera);
}
internal void RestoreMirrorActorLayers(Camera camera)
{
if (_activeMirrorRenderingCamera == camera)
RestoreMirrorActorLayers();
}
private void RestoreMirrorActorLayers()
{
for (int i = 0; i < MirrorCharacterSlotCount; i++)
if (_mirrorBoundCharacters[i] != null)
_mirrorBoundCharacters[i].RestoreMirrorChangedLayers();
_activeMirrorRenderingCamera = null;
}
private void OnBeginCameraRendering(ScriptableRenderContext context, Camera camera)
{
// Mirror cameras already have their own callbacks. Never overwrite a parent receiver scope.
if (!_mirrorRenderingCallbacksBound || GetMirrorCameraTarget(camera) != null)
return;
int layer = GraphicSettings.GetLayer(GraphicSettings.LayerIndex.LayerNO_VISIBLE);
if (layer < 0)
return;
for (int i = 0; i < _mirrorCameraTargets.Count; i++)
{
var target = _mirrorCameraTargets[i];
if (target.Mirror == null || !target.Mirror.IsInitialized || target.Mirror.BaseCamera == camera)
continue;
target.Mirror.SetMirrorObjectLayer(layer);
target.ReceiverCameras.Push(camera);
}
}
private void OnEndCameraRendering(ScriptableRenderContext context, Camera camera)
{
if (GetMirrorCameraTarget(camera) != null)
return;
for (int i = 0; i < _mirrorCameraTargets.Count; i++)
{
var target = _mirrorCameraTargets[i];
if (target.ReceiverCameras.Count == 0 || target.ReceiverCameras.Peek() != camera)
continue;
target.ReceiverCameras.Pop();
if (target.Mirror != null)
target.Mirror.ResetMirrorObjectLayer();
}
}
private void OnBeginBuiltInCameraRendering(Camera camera)
{
if (GraphicsSettings.currentRenderPipeline == null)
OnBeginCameraRendering(default, camera);
}
private void OnEndBuiltInCameraRendering(Camera camera)
{
if (GraphicsSettings.currentRenderPipeline == null)
OnEndCameraRendering(default, camera);
}
private void Awake()
{
_stageColorBlock = new UnityEngine.MaterialPropertyBlock();
@@ -204,6 +436,7 @@ namespace Gallop.Live
Director.instance._stageController = this;
TryBindTimelineCallbacks();
BindMirrorRenderingCallbacks();
}
// Laser 的 AlterUpdate 必须在 LiveTimelineControl 下发本帧 UpdateInfo 之后执行。
@@ -651,7 +884,7 @@ namespace Gallop.Live
return;
}
LaserController controller =_laserControllerArray[index];
LaserController controller = _laserControllerArray[index];
controller?.UpdateInfo(ref updateInfo);
}
@@ -833,7 +1066,7 @@ namespace Gallop.Live
return obj != null ? System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj) : 0;
}
}
private void AutoAddDriver(string shortTypeName)
{
Type t = null;
@@ -867,12 +1100,14 @@ namespace Gallop.Live
private void OnDisable()
{
UnbindMirrorRenderingCallbacks();
UnbindTimelineCallbacks(_boundTimelineControl);
_boundTimelineControl = null;
}
private void OnDestroy()
{
DestroyMirrorReflections();
UnbindTimelineCallbacks(_boundTimelineControl);
_boundTimelineControl = null;
}
@@ -1126,6 +1361,16 @@ namespace Gallop.Live
mirror.SetLightMirrorShader(!updateInfo.IsToonMirror);
mirror.MirrorReflectionRate = updateInfo.MirrorReflectionRate;
if (_mirrorRenderingCallbacksBound && updateInfo.EnableMirror)
{
var target = GetMirrorCameraTarget(mirror);
if (target != null)
{
target.BodyMask = (int)updateInfo.TargetChara;
target.HeadMask = (int)(updateInfo.EnableCharaHead ? updateInfo.TargetCharaHead : updateInfo.TargetChara);
}
}
mirror.ResetCullingMask();
if (_mirrorBgLayerMask != 0)
@@ -1169,33 +1414,10 @@ namespace Gallop.Live
foreach (var child in instance.GetComponentsInChildren<Transform>(true))
{
string objectName = child.name.Replace("(Clone)", "");
if (!StageObjectMap.ContainsKey(objectName))
{
if (child.name.IndexOf("light", StringComparison.OrdinalIgnoreCase) >= 0)
child.gameObject.SetActive(true);
StageObjectMap.Add(objectName, child.gameObject);
StageParentMap.Add(objectName, child.parent);
}
int objectHash = FNVHash.Generate(objectName);
if (!_objectsWorkInfoDictionary.TryGetValue(objectHash, out var works))
{
works = new List<StageObjectWorkInfo>();
_objectsWorkInfoDictionary.Add(objectHash, works);
}
works.Add(new StageObjectWorkInfo
{
transform = child,
originalParent = child.parent,
startTransform = new TransformBaseData
{
position = child.localPosition,
rotation = child.localRotation,
scale = child.localScale
},
renderers = child.GetComponents<Renderer>()
});
if (child.name.IndexOf("light", StringComparison.OrdinalIgnoreCase) >= 0 &&
!StageObjectMap.ContainsKey(child.name.Replace("(Clone)", "")))
child.gameObject.SetActive(true);
RegisterObjectTransform(child, string.Empty);
}
}
@@ -1214,6 +1436,67 @@ namespace Gallop.Live
washBeams.Initialize();
}
internal void RegisterObjectTransform(Transform child, string nameSuffixToken)
{
string objectName = child.name.Replace("(Clone)", "") + nameSuffixToken;
if (!StageObjectMap.ContainsKey(objectName))
{
StageObjectMap.Add(objectName, child.gameObject);
StageParentMap.Add(objectName, child.parent);
}
int objectHash = FNVHash.Generate(objectName);
if (!_objectsWorkInfoDictionary.TryGetValue(objectHash, out var works))
{
works = new List<StageObjectWorkInfo>();
_objectsWorkInfoDictionary.Add(objectHash, works);
}
var renderers = child.GetComponents<Renderer>();
for (int i = 0; i < renderers.Length; i++) CacheBgColor1Renderer(renderers[i]);
works.Add(new StageObjectWorkInfo
{
transform = child,
originalParent = child.parent,
startTransform = new TransformBaseData
{
position = child.localPosition,
rotation = child.localRotation,
scale = child.localScale
},
renderers = renderers
});
}
internal void UnregisterObjectTransform(Transform child, string nameSuffixToken)
{
string objectName = child.name.Replace("(Clone)", "") + nameSuffixToken;
int hash = FNVHash.Generate(objectName);
if (!_objectsWorkInfoDictionary.TryGetValue(hash, out var works)) return;
for (int i = works.Count - 1; i >= 0; i--)
{
if (works[i].transform != child) continue;
foreach (var renderer in works[i].renderers)
{
_bgColor1RendererProperties.Remove(renderer);
_ambientColorRenderers.Remove(renderer);
}
works.RemoveAt(i);
}
if (works.Count == 0) _objectsWorkInfoDictionary.Remove(hash);
if (StageObjectMap.TryGetValue(objectName, out var mapped) && mapped == child.gameObject)
{
if (works.Count > 0)
{
StageObjectMap[objectName] = works[0].transform.gameObject;
StageParentMap[objectName] = works[0].originalParent;
}
else
{
StageObjectMap.Remove(objectName);
StageParentMap.Remove(objectName);
}
}
}
private StageObjectUnit FindStageObjectUnit(int hash)
{
if (_stageObjectUnits == null) return null;
@@ -1594,19 +1877,7 @@ namespace Gallop.Live
if (r == null) continue;
_allStageRenderers.Add(r);
IndexRendererSharedMaterials(r);
int stageColorProperties = 0;
bool hasAmbient = false;
var materials = r.sharedMaterials;
for (int m = 0; m < materials.Length; m++)
{
var material = materials[m];
if (material == null) continue;
if (material.HasProperty(BgColor1MulColor0Id)) stageColorProperties |= 1;
if (material.HasProperty(BgColor1ColorPowerId)) stageColorProperties |= 2;
if (material.HasProperty(BgColor1AmbientColorId)) hasAmbient = true;
}
if (stageColorProperties != 0) _bgColor1RendererProperties.Add(r, stageColorProperties);
if (hasAmbient) _ambientColorRenderers.Add(r);
CacheBgColor1Renderer(r);
if (RendererHasAnyBgColorProps(r))
_bgColorAllEligibleRenderers.Add(r);
@@ -1620,6 +1891,23 @@ namespace Gallop.Live
}
}
private void CacheBgColor1Renderer(Renderer r)
{
int stageColorProperties = 0;
bool hasAmbient = false;
var materials = r.sharedMaterials;
for (int m = 0; m < materials.Length; m++)
{
var material = materials[m];
if (material == null) continue;
if (material.HasProperty(BgColor1MulColor0Id)) stageColorProperties |= 1;
if (material.HasProperty(BgColor1ColorPowerId)) stageColorProperties |= 2;
if (material.HasProperty(BgColor1AmbientColorId)) hasAmbient = true;
}
if (stageColorProperties != 0) _bgColor1RendererProperties[r] = stageColorProperties;
if (hasAmbient && !_ambientColorRenderers.Contains(r)) _ambientColorRenderers.Add(r);
}
private void IndexRendererSharedMaterials(Renderer r)
{
var mats = r.sharedMaterials;
@@ -30,6 +30,16 @@ namespace Gallop.RenderPipeline
_parameter = new PostImageEffectFeature.Parameter();
}
public void UpdateImageEffectParameter()
{
// Native RVA 0x1a0da30; recomputed again before each render.
ref var dof = ref Parameter.DofDiffuionBloomOverlay;
dof.IsDisableDofTemporary = dof.IsEnableDofAutoDisable &&
dof.DofFocalSize >= dof.DofMaxFocalSize;
dof.DecideDrawType(dof.IsEnableDof && !dof.IsDisableDofTemporary &&
GallopImageEffect.UserDofEnabled);
}
private void Awake()
{
Initialize(false);
@@ -59,8 +59,8 @@ namespace Gallop.RenderPipeline
set => _enableRendering = value;
}
// Shared live state. Director updates this object from the timeline;
// each camera's CameraData points at the same state before Setup runs.
// Active-camera publication alias, not storage shared by every camera.
// GallopImageEffect / MultiCamera retain their own CameraData parameters.
private static Parameter _runtimeParameter = new Parameter();
public static Parameter RuntimeParameter
@@ -71,6 +71,7 @@ namespace Gallop.RenderPipeline
_runtimeParameter = new Parameter();
return _runtimeParameter;
}
internal set => _runtimeParameter = value;
}
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
@@ -220,12 +221,14 @@ namespace Gallop.RenderPipeline
if (!camera.TryGetComponent(out cameraData))
cameraData = camera.gameObject.AddComponent<CameraData>();
// The recovered feature expects CameraData.Parameter. Keep it
// bound to the timeline-owned object and refresh the active camera
// every frame because CameraSwitcher can replace it.
var cameraParameter = multiCamera != null ? multiCamera.PostEffectParameter : RuntimeParameter;
// Bind this camera's owned state before deciding draw type.
// Live auto-disable must never leak through the active-camera alias.
var imageEffect = camera.GetComponent<GallopImageEffect>();
var cameraParameter = multiCamera != null ? multiCamera.PostEffectParameter
: imageEffect != null ? imageEffect.RenderParameter : RuntimeParameter;
cameraData.Parameter = cameraParameter;
cameraParameter.TargetCamera = camera;
cameraData.UpdateImageEffectParameter();
Parameter parameter = ResolveFeatureParameter(cameraData);
if (parameter == null)
@@ -16,16 +16,21 @@ namespace Gallop.RenderPipeline
public Vector3 InitialPosition;
public int NameHash;
public Material Material;
public MeshRenderer Renderer;
public bool HasColorPower, HasMulColor0;
public Color ColorFactor = Color.white;
public float BrightnessFactor = 1f;
public bool AutoBrightness = true;
public bool ScreenFit;
public bool HasBlinkColor;
public Color BlinkColor;
}
private readonly Dictionary<int, List<Target>> _groups = new Dictionary<int, List<Target>>();
private readonly List<Target> _targets = new List<Target>();
private readonly Dictionary<CustomLensFlare, Target> _bySource = new Dictionary<CustomLensFlare, Target>();
private readonly Plane[] _frustumPlanes = new Plane[6];
private readonly MaterialPropertyBlock _lightProperties = new MaterialPropertyBlock();
private readonly float _standard;
private readonly float _under;
private readonly int _colorPowerId;
@@ -38,6 +43,11 @@ namespace Gallop.RenderPipeline
_under = under;
_colorPowerId = ShaderManager.GetPropertyId(ShaderManager.PropertyId._ColorPower);
_mulColor0Id = ShaderManager.GetPropertyId(ShaderManager.PropertyId._MulColor0);
AddSources(root, nameSuffixToken);
}
public void AddSources(Transform root, string nameSuffixToken)
{
if (root == null) return;
foreach (var flare in root.GetComponentsInChildren<CustomLensFlare>(true))
{
@@ -52,10 +62,12 @@ namespace Gallop.RenderPipeline
InitialPosition = sourceTransform.localPosition,
NameHash = FNVHash.Generate(flare.name + nameSuffixToken),
Material = material,
Renderer = renderer,
HasColorPower = material != null && material.HasProperty(_colorPowerId),
HasMulColor0 = material != null && material.HasProperty(_mulColor0Id)
};
_targets.Add(target);
_bySource.Add(flare, target);
if (sourceTransform.parent == null) continue;
// Native strips every literal Clone token from the parent only.
int parentHash = FNVHash.Generate(sourceTransform.parent.name.Replace("(Clone)", string.Empty) + nameSuffixToken);
@@ -68,6 +80,34 @@ namespace Gallop.RenderPipeline
}
}
public void RemoveSources(Transform root, string nameSuffixToken)
{
for (int i = _targets.Count - 1; i >= 0; i--)
{
var target = _targets[i];
if (target.Transform == null || !target.Transform.IsChildOf(root)) continue;
var parent = target.Transform.parent;
if (parent != null)
{
int hash = FNVHash.Generate(parent.name.Replace("(Clone)", string.Empty) + nameSuffixToken);
if (_groups.TryGetValue(hash, out var group))
{
group.Remove(target);
if (group.Count == 0) _groups.Remove(hash);
}
}
_targets.RemoveAt(i);
_bySource.Remove(target.Flare);
}
}
internal void SetBlinkColor(CustomLensFlare flare, Color color)
{
if (flare == null || !_bySource.TryGetValue(flare, out var target)) return;
target.HasBlinkColor = true;
target.BlinkColor = color;
}
public void Apply(ref LensFlareUpdateInfo info)
{
if (_groups.TryGetValue(info.TimelineNameHash, out var group))
@@ -110,8 +150,23 @@ namespace Gallop.RenderPipeline
Color color = target.ColorFactor;
if (target.Material != null)
{
Color materialColor = target.HasMulColor0 ? target.Material.GetColor(_mulColor0Id) : Color.white;
float colorPower = target.HasColorPower ? target.Material.GetFloat(_colorPowerId) : 1f;
// Stage lighting uses property blocks instead of changing the material.
// Read the same first-slot values that the authored source mesh draws.
_lightProperties.Clear();
if (target.Renderer != null)
{
target.Renderer.GetPropertyBlock(_lightProperties, 0);
if (_lightProperties.isEmpty)
target.Renderer.GetPropertyBlock(_lightProperties);
}
Color materialColor = target.HasBlinkColor ? target.BlinkColor : target.HasMulColor0
? _lightProperties.HasColor(_mulColor0Id)
? _lightProperties.GetColor(_mulColor0Id) : target.Material.GetColor(_mulColor0Id)
: Color.white;
float colorPower = target.HasColorPower
? _lightProperties.HasFloat(_colorPowerId)
? _lightProperties.GetFloat(_colorPowerId) : target.Material.GetFloat(_colorPowerId)
: 1f;
color *= materialColor * (colorPower * 2f);
}
bool visibleColor = color.r > 0.000001f || color.g > 0.000001f || color.b > 0.000001f;
-408
View File
@@ -1,408 +0,0 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
UmaViewer is a Unity application (2022.3.62f1) that loads and displays assets from Uma Musume: Pretty Derby. It reads encrypted asset bundles directly from the game installation without modifying game files.
## Development
**Open the project:** Unity Hub → Add → `C:\Users\riten\Desktop\UmaBuild`
**Run:** Open `Assets/Scenes/Version2` scene → Play in Unity Editor
**Build:** File → Build Settings → PC Standalone → Build
No CLI build commands — Unity Editor is required.
## Game Data & Asset Pipeline
Game assets are encrypted. Key files:
- `meta` (SQLite-MC ChaCha20 encrypted) — maps bundle names → hash filenames in `dat/`
- `dat/{2-char-prefix}/{hash}` — encrypted asset bundles, each with a per-bundle XOR key from meta
**Bundle decryption** (`UmaAssetBundleStream.cs`): header (first 256 bytes) is plain; bytes ≥256 are XOR'd with `FKey = ABKey[i] XOR bundleKey_bytes[j]`.
**meta DB decryption**: `UmaDatabaseController.ReadMetaFromEncryptedDb()` uses `sqlite3mc_x64.dll` with cipher=3 (ChaCha20). Final key = `DBKey[i] XOR DBBaseKey[i % 13]`.
**Asset bundle paths** (key formats):
- Live cutt timelines: `cutt/cutt_son{music_id}/cutt_son{music_id}`
- Live effect prefabs: `3d/effect/live/pfb_{effectName}`
- Stage prefabs: `3d/env/live/live{bgId}/pfb_env_live{bgId}_controller000`
**Python tools** (`tools/`) — rebuilt 2026-08-04 after the old `UmaCrack\` toolchain was deleted. Run with `~/.venvs/umatools/bin/python3` (needs `UnityPy` + `apsw-sqlite3mc`, **not** plain `apsw`; see `tools/requirements.txt`).
| Script | Use |
|---|---|
| `uma_common.py` | Library: key constants, `decrypt_bundle_bytes()`, `MetaDb` (path→hash, UnityPy load) |
| `dump_meta.py` | `plain` → `out/meta_plain.db` · `find <LIKE>` · `info <path>` (hash, dat path, deps, `[NOT DOWNLOADED]`) · `songs` |
| `dump_bundle.py` | `list` / `tree` / `json` / `save` / `gameobjects`, `--deps` |
| `dump_cutt_typetree.py` | **Authoritative track schema.** `--fields <song>` · `--tree <field> <song>` · `--sample <field> <song>` · `--groups` |
| `scan_live_tracks.py` | All 59 songs → `out/scan_keys.csv`, `scan_groups.csv`, `scan_summary.txt`, `scan.json` (~21 s) |
Notes: `meta` decrypts via sqlite3mc `PRAGMA cipher='chacha20'` + `PRAGMA hexkey='<64 hex>'` (the `key=x'...'` and `raw:` forms both fail); `VACUUM INTO` re-encrypts the target, so `dump_meta.py plain` copies schema+rows explicitly.
**Cutt bundles ship full TypeTrees, so field names and keyframe counts from these tools are ground truth.** All 70 worksheets across all 59 songs share one 128-field schema — no version drift. Only `son<id>_camera` and `type_01..type_10` carry the trees; the `cutt_son<id>` prefab and `data` bundles are stripped.
**Getting a track's real field name without the dump tools** — Unity matches bundle TypeTree fields by name, case-sensitively. A field whose name doesn't match is never populated (it does *not* become null — Unity initialises every serialised `List<T>` to an empty list, so null-vs-empty tells you nothing). To test a candidate name, declare it on `LiveTimelineWorkSheet` and check whether it receives keys:
```csharp
LiveTimelineWorksheetDiag.Probe(sheet, "candidateFieldName");
```
Unsure about casing? Declare both spellings side by side — only the correct one fills. This is how `WashLightList` (capital W) was confirmed; note upstream katboi01 uses `washLightList`, which never populates.
## Live Timeline Architecture
The Live playback system is in `Assets/Scripts/umamusume/Gallop/Live/`:
```
Director.cs ← singleton, wires everything together
Cutt/
LiveTimelineControl.cs ← dispatches timeline events each frame (~1900 lines)
LiveTimelineWorkSheet.cs ← all track data fields (ScriptableObject)
LiveTimelineDataList/ ← one .cs per track type
UpdateInfo/ ← structs passed to event handlers
StageController.cs ← manages stage GameObjects, StageObjectMap
```
**Track implementation pattern** (repeat for each new track):
1. Add data class in `LiveTimelineDataList/` (extend `LiveTimelineKeyWithInterpolate` for key, add group wrapper implementing `ILiveTimelineGroupDataWithName`)
2. Add `[SerializeField] public List<...> trackList;` to `LiveTimelineWorkSheet`
3. Add `public event Action<TData, TKey> OnUpdateXxx;` in `LiveTimelineControl`
4. Call `AlterUpdate_SimpleListControl(workSheet.trackList, d => d.keys, OnUpdateXxx, _currentFrame)` in `AlterLateUpdate()`
5. Subscribe `_liveTimelineControl.OnUpdateXxx += handler` in `Director.InitializeTimeline()`
**Important:** `LiveTimelineKeyWithInterpolate` already declares `frame`, `attribute`, `interpolateType`, `curve`, `easingType` — do NOT redeclare these in subclasses.
**Stage shader colour channels** (enumerated at runtime via `Shader.GetPropertyType`, confirmed on stage live10149 / song 1177):
| shader | colour | brightness | other |
|---|---|---|---|
| `Gallop/3D/Live/Stage/DefaultNoAmbient` | `_MulColor0` | `_ColorPower` | |
| `Gallop/3D/Live/Stage/DefaultEnvMapNoAmbient` | `_MulColor0` | `_ColorPower` | `_AddColor`, `_EnvMap` |
| `Gallop/3D/Live/Stage/DefaultTransparentNoAmbient` | `_MulColor0` | `_ColorPower` | `_AmbientColor` |
| `Gallop/3D/Live/Stage/LightBlinkBlend` | `_BlinkLightColor` | `_ColorPower` | `_SrcBlend`/`_DstBlend` |
| `Gallop/3D/Live/Stage/LightBlend` / `LightAdd1` | `_MulColor0`, `_MulColor1` | `_ColorPower`, `_ColorPowerMultiply` | |
| `Gallop/3D/Live/Stage/Laser` | `_MulColor0`, `_MulColor1` | `_ColorPower` | `_RandomValue` |
| `Gallop/3D/Bg/BgMirrorBall` | `_MulColor0` | **(none)** | |
| `Gallop/3D/Live/Stage/StageMirrorBallShine` | (none) | | |
| `Gallop/3D/Live/Stage/StageTransmittedLightMask` | (none) | | `_TransmittedLightMaskScale` |
**Brightness is a separate channel — do not fold it into the colour.** Write the key's colour to the colour property and its `power` to `_ColorPower`; let the shader combine them. Only fall back to `colour * power` where `_ColorPower` is absent (`BgMirrorBall`).
**Writing shader properties: one shared block, always Get → modify → Set.** All of `Director`'s
handlers write through the single `PropBlock` (`Director._propBlock`) and must call
`renderer.GetPropertyBlock(block)` first — `SetPropertyBlock()` **replaces** the block rather than
merging, so a handler that starts from an empty block wipes whatever another track wrote to the
same renderer earlier in the same frame. That is exactly how GlobalLight was silently dead for
59/59 songs (BgColor1's character branch runs right after it and cleared all 13 rim properties).
Never `new MaterialPropertyBlock()` per frame, and never write `_Color` without first checking the
target shader's real property table — three separate tracks shipped no-op colour writes that way.
Dump any shader's real property table with:
```python
# tools/, via ~/.venvs/umatools/bin/python3
env = MetaDb().load("shader") # 499 shaders
pf = obj.read_typetree()["m_ParsedForm"] # m_Name, m_PropInfo.m_Props
```
**`_MulColor0` is on every stage shader and is BgColor1's channel; `_AmbientColor` belongs to BgColor2.** They are separate properties on the same shader, so the two tracks must not write the same one. Same naming family as WashLight's `MulColor0` and UVScrollLight's `mulColor1`.
⚠️ A material's `m_SavedProperties` in the bundle lists properties it no longer has — it retains entries from whatever shader it was authored against. `Material.HasProperty()` asks the *current shader*. Always enumerate the shader, never trust the bundle's saved-property table.
**渲染状态也从这张过期表里读,后果最严重。** Gallop 的发光类 shader 把混合写成
`Blend [_SrcBlend] [_DstBlend]`,也就是**从材质属性取渲染状态**。live10149 的
**26/26 个材质**存的都是 `_SrcBlend=One, _DstBlend=Zero`(不透明覆盖),且每一个的 float 表里
都带着 `_WorkflowMode`/`_Surface`/`_ClearCoatMask`/`_Smoothness`/`_Blend` —— 那是 **URP Lit
的属性表**,整批盖上去的,One/Zero 正是 URP Lit 的不透明预设。
作者意图可查:全库 16 个声明这两个属性的 shader 里,**14 个默认 `One/One`(加法混合)** ——
`LightBlinkBlend`、`LightBlend`、`StageBeamLight{,Cutoff,Fadeout}`、
`StageLightBlink{Cutoff,Fadeout}`、`StageProjectorBlend{,VertexAlpha,AnimVertexAlpha}`、
`StageMonitorBlend*`、`MirrorBallProjector`、`BgUnlitStencilAlpha`,全是发光/投影那一批。
被压成不透明后,加法光柱「颜色为黑 = 什么都不加 = 不可见」变成了**一堵实心黑墙**。
⚠️ **实际受害面比存档表窄得多,别照着 26 这个数推。** 只有**当前 shader 真的声明了**这两个
属性的材质才会被读到;其余材质虽然也存着 `One/Zero`,但那只是过期条目,无人问津。
live10149 实测(`[StageBlend]` 日志):31 个材质里**只有 1 个**被修正 ——
`mtl_env_live10149_blinklight000` / `LightBlinkBlend`,`_DstBlend` 0 → 1。
**但「1 个材质」严重低估了影响面 —— 材质在舞台上是高度共享的。** 那一个材质铺满
27 个 BlinkLight 组、约 **1450 个渲染器**(观众席 95、mob000 570、glow_object 67、
glow_ramp 58、镜面球闪片 83、全部 wash 组、各种 LED 板),实机确认修好的不只是地面 wash 灯的
黑楔子,长期挂着的「小灯泡渲染成黑块」也一并正常了。
**教训(第三次同一天):报数要报对单位。** 舞台上约 1500 个渲染器只有 31 个材质,
按材质计数会把影响面说小两个数量级 —— `[StageBlend]` 日志现在同时报渲染器数。
`StageController.RestoreAuthoredBlendState()` 在舞台初始化时把这两个属性写回 **shader 声明的
默认值**(`Shader.GetPropertyDefaultFloatValue`),对本来就该不透明的 shader 是空操作,自限。
改了哪些材质会逐条打进 `[StageBlend]` 日志。
> 教训比这个 bug 本身通用:**过期存档表不只影响颜色,还能改渲染状态**。
> 看到「本该发光的东西是黑的/挡住后面的东西」,先查 `_SrcBlend`/`_DstBlend`,
> 再查颜色写对没有。
Worked example — `mtl_env_live10149_projector001` (shader `Gallop/3D/MirrorAndShadow/MirrorBallProjector`, 22 real properties) saves 40+, including Standard-shader leftovers (`_Glossiness`, `_Metallic`, `_Parallax`, `_Mode`, `_UVSec`) **and** four plausible-looking ghosts the current shader never declares: `_IsLoopYRotation`, `_LoopYRotationSpeed`, `_MirrorBallProjectionIntensity`, `_MirrorBallRotateWS`. Two of those are older spellings of properties that *do* exist (`_MirrorBallIsLoopRotation`, `_MirrorBallLoopRotationSpeed`) — exactly the kind of near-miss that reads as a discovery. Note also that where a component field and a saved property disagree (`MirrorBallFallOffPower` = 1.0 on the component vs `_MirrorBallFalloffPower` = 2.0 in the material), the component wins at runtime: these controllers push their own fields into the material.
**Track group names are not always GameObject names.** Four separate silent failures were traced to this in one session, so check the mapping before assuming a track is unimplemented:
- a whitelist filter in the dispatcher dropped 92% of BgColor1's keys (`validBgColorNames`)
- `StageObjectMap` dedupes by name, so a crowd of 66 same-named objects only ever got its first member
- the Object track's `neonsign` is a `_stageObjectUnits` **unit name**, not a GameObject — no object of that name exists
- `ObjectUpdateInfo.OffsetType` was populated by the dispatcher but never read by `StageController`, so `Add`-relative positions were written as absolute
All four failed silently, with no error. Treat a track that "works" but looks wrong as a routing problem first.
**StageObjectMap:** Stage child GameObjects are indexed by name. Objects whose names match `IsTimelineControlledLight()` (`blinklight`, `spotlight3d`, `_wash_`, `laser`) start `SetActive(false)` — their handlers call `SetActive(true)` when the track fires. All other objects (neonsigns, glow meshes, UV scroll objects, etc.) keep their prefab default state.
## Ground-truth sources: what is recoverable and what is not
Mapped 2026-08-05. **Check this list before declaring something "unknown"** — several things
previously written off as un-reversible are in fact dumpable, and one whole class of problem
was solved by realising the game's own scripts can be re-bound.
### Available
| 来源 | 给出什么 | 怎么取 |
|---|---|---|
| cutt bundle TypeTree | 128 个轨道字段名 + 全部关键帧值,59 首全带 | `tools/dump_cutt_typetree.py` |
| 舞台 prefab TypeTree | GameObject 层级、组件构成,**以及缺失脚本 MonoBehaviour 的字段名和值**(离线可读) | `MetaDb().load('3d/env/live/liveNNNNN/pfb_..._controller000')` |
| shader bundle | 499 个 shader 的真实属性表(名/类型/默认值/range) | 枚举 `m_ParsedForm.m_PropInfo.m_Props` |
| material bundle | 材质的 shader 绑定与存档属性(⚠ 存档表含过期条目,见下) | `sourceresources/3d/env/live/liveNNNNN/materials/mtl_*` |
| AnimationClip | 曲线的 path / 目标属性 / 关键帧时间与值 | `m_RotationCurves` 等 |
| MonoScript | **类名 + namespace + 程序集名** | 见下,这是最重要的一条 |
### ⭐ 用原签名重建脚本,可直接拿到真实序列化字段
舞台 prefab 引用了 11 个脚本类,UmaViewer 起初只实现了 `StageController`,其余 892 个
MonoBehaviour 实例脚本为空。**但这些脚本是可以「接管」的** —— Unity 按
**类名 + namespace + 程序集名** 解析 MonoScript,而 `Assets/Scripts/umamusume.asmdef`
的程序集名正是 bundle 里写的 `umamusume`。所以只要按签名建类,字段就会被真正反序列化进来。
已验证:新建 `Gallop.Live.BillboardController` 后,`[StageScripts]` 的「脚本丢失」
从 **892 降到 728**(正好 −164 个实例),`_rotationType` 等字段直接可读。
签名清单(`Assets/Scripts/` 下任意位置均可,只要在 umamusume 程序集内):
| namespace | 类 | live10149 实例数 | 状态 / 已 dump 到的字段 |
|---|---|---|---|
| `Gallop.Live` | `AnimationObjectController` | 282 | ❌ **别建,建了也没用**:实测序列化字段 **一个都没有**(282 个实例全空)。重建只会让「脚本丢失」892→446,拿到 0 bit 新信息 —— 它是纯行为类,播哪个 clip / 何时播 / 多快全在拿不到的方法体里。顶替版已于 2026-08-07 撤除,舞台 Animation 现在**有意不播**,见下 |
| `Gallop.Live` | `UnityLensFlareController` | 205 | ❌ 只有 1 个字段 `_enableAngleDegree`(0),本体不在这里 |
| `Gallop.Live` | `BillboardController` | 164 | ✅ 已建(字段已读到,朝向行为待定)|
| `Gallop.Live` | `WashLightController` | 27 | ❌ 24 个字段全是具体数值 + 两张投影贴图(`_projectionTexture`/`_cameraProjectionTexture`),缺的是 URP 下的投影实现 |
| `Gallop.Live` | `LightProjection` | 4 | ❌ 只有 `_projectionType`(1) |
| `Gallop.RenderPipeline` | `CustomLensFlare` | 200 | ❌ **数据最完整、最值得做的一个**,见下 |
| `Gallop.RenderPipeline` | `MirrorBallProjector` | 4 | ❌ 字段已 dump 但**运行时绑定不可见**,见 Blocked |
| `Gallop.RenderPipeline` | `CustomProjector` | 4 | ❌ 就是一套 legacy `Projector` 参数(near .1 / far 60 / fov 30 / aspect 1 + `Material`)|
| `Gallop` | `MirrorReflection` | 1 | ✅ 已建并实现(平面镜反射,见下)|
| `Gallop.Live.ShaderParam` | `ShaderParamController` | 1 | ⚠ **不值得做**:实测只有 `_AmbientColor`/`_CharaColor` 两个向量,值都是 (1,1,1,1),实现出来是空操作 |
**LensFlare 这条线数据是齐的**(这也是目前性价比最高的一块):
- `CustomLensFlare` 字段:`Flare`(PPtr) / `Brightness` / `FadeSpeed` / `Color` / `IgnoreLayers` / `IsDirectional`。
- `Flare` 指向的**不是** Unity 内置 `Flare` 资产,而是 `Gallop.RenderPipeline.LensFlareData`
这个 ScriptableObject(同样在 umamusume 程序集里,照样可以按签名重建)。
路径形如 `sourceresources/3d/env/live/common/lensflare/flare013/flares/flare013_00`。
- 它的字段是 Unity legacy Flare 的逐字翻版:
`TextureLayout` / `Texture` / `ElementArray[{ImageIndex, Position, Size, Color, UseLightColor,
Rotate, Zoom, Fade}]` / `UseFog`。**所以语义不受 IL2CPP 阻塞** —— 这些是 Unity 自己的概念。
- live10149 上 199 个物件同时挂 `CustomLensFlare` + `UnityLensFlareController` + MeshRenderer,
另有 5 个只挂 `UnityLensFlareController`。舞台上**没有任何 legacy `LensFlare` 组件**,
原版是自己画的。URP 侧对应物是 `LensFlareComponentSRP` + `LensFlareDataSRP`。
字段名必须和 TypeTree 逐字一致(大小写敏感),dump 一下即可。
这条同样适用于任何其它 bundle 里的 MonoBehaviour。
**重建签名只拿得到数据,拿不到方法体。** 两个已建的类正好是两种情形:
- `MirrorReflection`(`Assets/Scripts/umamusume/Gallop/MirrorReflection.cs`)—— 接收端能
自己查出来,所以能补完行为:宿主 `mirror_a` 的材质用 `Cygames/MirrorAndShadow/ReceiveMirror`,
该 shader 只有 `_MainTex`/`_ReflectionTex`/`_Color`/`_ReflectionRate`,而组件字段
`_mirrorReflectionColor`/`_mirrorReflectionRate` 与后两者逐字对应。实现方式是第二摄像机
+ 反射矩阵 + 斜投影渲进 RT 再写回 `_ReflectionTex`(URP 下不能用 `Camera.Render()`,
必须挂 `beginCameraRendering` 拿 `ScriptableRenderContext` 后 `RenderSingleCamera`)。
这同时解决了长期的「地板发白」——`_ReflectionTex` 未绑定时 Unity 代入白贴图,
而 `_ReflectionRate` 默认 1.0,等于满强度白反射。
- `BillboardController` —— 字段读到了,**但行为写了一版又关掉了**,这是「重建签名」的能力边界。
`_rotationType == 0` 是不是「整轴朝向摄像机」、朝向该用摄像机 up(跟镜头 roll)还是世界 up
(只绕 Y),都没有 ground truth;实机看是「一直转来转去,而那东西不该转」,
于是 `BillboardController.EnableRotation` 默认 false,面片保持 prefab 作者摆好的朝向。
同一次排查里揪出一个**确定的** bug(已修):目标摄像机只解析了一次就缓存,
而生效摄像机随 CameraSwitcher 每帧变 —— 切换后面片朝的是观众看不见的那台,
那台还在自己动,看上去就是无缘无故乱转。**凡是引用「当前摄像机」的舞台脚本都要注意这条。**
**舞台自带 Animation 有意不播**(283 个组件,2026-08-07 撤除了替代实现):
它们全部 `playAutomatically = true` 但默认 clip 为空,原版靠 `AnimationObjectController`
显式 `Play()`,而那个类**零序列化字段**,纯行为,方法体拿不到 —— 「播哪个 / 何时播 / 多快」
没有任何数据能还原。写过一版 `StageAnimationPlayer` 顶替,策略是「只有一个 clip 就播」,
错在把「这物件只有一个**状态**」当成「这个状态**一直在播**」(后者正是那个缺失的类每帧做的
决定):wash 灯 2 秒一个来回疯狂摆头(原版不扫只闪),镜面球转速无从校验。已整体撤除。
**完整理由与复活条件见 `LIVE_TRACKS.md` →「舞台自带 Animation 为什么不播」专条。**
⚠ 撤除时唯一保留下来的结论:**驱动舞台动画不要用 `Animation.Play()`**,
那跑 Unity 自己的时钟,暂停/拖动进度条都会脱节;应每帧把 `AnimationState.time` 设成
`LiveTimelineControl.currentLiveTime`(秒)再 `Sample()`。将来重做直接用这条。
### 🔎 舞台上「行为不对」的第一嫌疑:缺组件,不是解析错
**这是分诊规则,不是某一次的结论。** 舞台 prefab 引用 11 个脚本类,至今仍有 **728 个
MonoBehaviour 实例是空的**(基线 892,已补 `BillboardController` −164)。其中
`AnimationObjectController` 一家就占 282 个实例 —— 舞台上所有「什么时候动、动多快、
动哪一个」的决定原本都在它手里,而它整个不存在。
所以当某个舞台元素表现不对(该动的不动、不该动的在动、动的节奏不对),
**默认假设应该是「原版那个组件缺失,现在由我们猜的行为顶着」,而不是「数据解析错了」**。
理由是可检验的:字段值、clip 曲线、shader 属性表这些**数据**层面的东西全都能 dump 出来核对,
而且一路核对下来**基本都是对的**;反复出错的是**行为**层面 —— 那正好是拿不到方法体的部分。
已经有两个同形状的例子,都是「物件选对了、行为猜错了」:
| 现象 | 数据对不对 | 真实原因 |
|---|---|---|
| wash 灯疯狂摆头 | clip 曲线完全正确(实测 90°→0°→90°) | 缺 `AnimationObjectController`,我们替它决定了「一直播」 |
| 面片一直乱转 | 字段全部正确读到 | 缺原方法体,`_rotationType==0` 的语义是我们猜的 |
推论一:动手前先查一眼**这个物件挂过什么脚本、那个脚本我们有没有**
(`[StageScripts]` 日志 + `CLAUDE.md` 的签名清单),比直接怀疑解析快得多。
推论零:**先 dump 一眼那个缺失组件有没有字段,再决定值不值得重建。**
`AnimationObjectController` 实测**零字段**(282 个实例全空),所以重建它拿不到任何信息,
舞台动画的那些时机问题不可能靠「把原类建出来」解决 —— 这个方向是死的,
别再试。反过来 `CustomLensFlare` 字段齐全(还牵出 `LensFlareData`),就非常值得建。
判断只要一条命令,不要凭实例数多就以为收益大。
推论二:**顶替缺失组件时,要把「我在替谁做决定」写清楚**,并且区分
「从 bundle 数据推出来的」和「看参考视频观察到的」—— 后者是有效证据,但不是 ground truth,
换个舞台可能就不成立。(反面教材:舞台动画的 `_wash_` 排除规则就是这么来的,
后来连同整个替代实现一起撤掉了 —— 观察能证伪一个实现,但支撑不起一个实现。)
反例也要记住:**并非所有舞台画面问题都是缺组件。** 光柱渲染成黑墙那次,
根因是材质被盖了 URP Lit 的属性表、`_DstBlend` 从 One 变成 Zero,
把加法混合压成了不透明 —— 那是**数据**问题,而且是 dump 得出来的(见下)。
分诊规则的意思是「先查缺不缺组件」,不是「一律归咎于缺组件」。
### Blocked
**IL2CPP 元数据拿不到。** 游戏是 IL2CPP 构建,但 `global-metadata.dat` 既不在
`umamusume_Data/il2cpp_data/`(那里只有 `Resources/`),也没嵌在 `GameAssembly.dll` 里
—— 魔数 `0xFAB11BAF` 零命中,`BillboardController` / `_rotationType` 等标识符字符串
也全部搜不到。这是该游戏已知的反篡改,元数据运行时才还原。
因此以下**永远拿不到标准答案**,只能靠交叉验证或承认未知:
- **游戏自己定义的枚举语义** —— `_rotationType`(0/2)、`LightBlendMode`、`CmnColorType0/1`、
BlinkLight 的 `pattern`、`ColorType` 等。字段值读得到,含义读不到。
⚠ 但**先分清是谁的枚举**:`LensFlareData.TextureLayout` 长得像这一类,其实是 Unity
legacy `Flare` 资产的 `FlareTextureLayout`,语义在 Unity 侧公开,不受此限。
- **对象之间的运行时绑定** —— 重建签名只能拿到**数据**,拿不到原方法体,所以「这个组件
跑起来去找谁」是不可见的。实例:`MirrorBallProjector` 的 shader 需要
`_MirrorBallPosWS`/`_MirrorBallScale`/`_MirrorBallRotateValue`,而组件里**没有任何指向
灯球的引用字段**,4 个 projector 全在原点、共用同一个材质,灯球却散布在 6 个位置。
绑定关系只存在于方法体里。
- **速度/系数一类的常量** —— 如果原版在代码里对动画做了调速,那个倍率无从得知。
(注意这条不要滥用:镜面球转速一度被记成此类,实测其实完全确定,见下。)
- 未随包发布的 shader(PostFilm 的定义性 shader 就在 app 二进制里)。
**「灯球转速」到底确定到什么程度(2026-08-07,当天两次修正)**
⚠️ **先说结论的边界**:clip 里的转速是硬数据,**但「原版按 1.0 倍速播这条 clip」不是**。
实机跑下来观察是「所有迪斯科灯球还是太快」,也就是说原版多半有个播放倍率或者压根不用
这条 clip 驱动球体 —— 那正是本节上面「速度/系数一类的常量」说的那类不可知量。
下面的数字只证明「**我们忠实地播了这条 clip**」,不证明「和原版一致」。
已确定的部分:
- live10149 的 4 个 `MirrorBallProjector` 实例**全部** `MirrorBallIsLoopRotation = 0`、
`MirrorBallLoopRotationSpeed = 0`、`MirrorBallLoopRotationValue = 0` ——
shader 自带的 loop-rotation 通路在这个舞台上是**关掉的**,不是转速来源。
- 真正在转的是 clip `anm_env_live10149_blinklight_mirrorball_flarelight_loop_000`:
6 条 quaternion 曲线(`mirrorball_a_000` + `b_000..004`),7 个关键帧,
**恒定 −179.50°/s 绕 Y**(每个关键帧算出来都是这个数),2.0 s 一圈,wrapMode = Loop。
末帧 −359° 而不是 −360°,是为了循环接缝不重复一帧。
- 曾接管过这条 clip,采样用的 `currentLiveTime` 单位是秒(帧号 = ×60),**没有单位换算错误**,
放出来就是 clip 写的 2.0 s 一圈 —— 但实机仍然偏快,这正是下面第 2 条教训的由来。
该实现已于 2026-08-07 撤除,球现在不转。
两条教训,方向相反,都要记:
1. 把「值是 0」当成「值未知」是两回事 —— dump 之前先看一眼开关字段
(`MirrorBallIsLoopRotation` 就是那个开关)。
2. **但「clip 的转速是确定的」推不出「转速问题解决了」**。我上一版文档写成了
「我们的构建里转速本来就是对的」,实机观察当天就否掉了它。
数据确定的是**素材**,不是**原版怎么用这个素材**;中间那个倍率仍然是不可知量。
### ⚠ 现象描述不是 ground truth
字段值、shader 属性表是硬数据;**「哪个物件看起来不对」不是** —— 文档里的现象描述往往
没经过验证。地板发白排查栽在这上面:文档记着 `plane_000` / `stage_object_001` /
`specular_002` 发白,整轮排查都围着这三个转,最后查明白的其实是**叠在同一位置的
`mirror_a`**(同在 `pfb_env_live10149_main000` 下、局部变换全为单位,肉眼分不出)。
它用 `Cygames/MirrorAndShadow/ReceiveMirror`,`_ReflectionRate` 默认 1.0 而
`_ReflectionTex` 从没赋值 —— Unity 对未绑定采样器代入白贴图,满强度白反射。
期间那个「把 `_EnvRate` 归零无变化」的实验因此也是误导:切的是另一批物件。
**排查视觉问题的第一步应该是确认现象归属于哪个物件**(让代码把可疑物件隔离/高亮),
而不是从文档里的名字出发。
### 间接手段(已被证明有效)
拿不到直接答案时,**相关性交叉验证**多次奏效,比猜测可靠得多:
- BlinkLight 调色板槽位规则:靠「物件名 `lightNNN_`/`alphaNNN_` 前缀的种数」与
「调色板里去重颜色数」在**每一组都精确相等**推出,7 组无一例外。
- BgColor1 的通道 `_MulColor0`:靠枚举 shader 属性表 + 排除法确认。
- 「某属性存在」≠「目标 shader 上有该属性」—— `_Color` 空写连续栽了三次
(BlinkLight / Spotlight3d / UVScrollLight),扫一遍 shader 属性表即可批量排查。
## Working rule: no ground truth, no implementation
Field names, keyframe values and shader property tables are all recoverable from the bundles
(`tools/`), so **verify before you write code** — and when something genuinely cannot be
recovered, leave it unimplemented with a TODO rather than guessing a value.
Guessing has cost real time in this project: the PostFilm vignette geometry was guessed twice
(full-screen wash, then a huge border) before it turned out the defining shader isn't shipped in
any bundle. `PostFilmRendererFeature._enableRendering` is now `false` for exactly this reason.
Note the distinction that has caught me out: *"the property exists"* is not *"this field maps to
that property"*. `_ColorPower` is present on the stage shaders, but there is no evidence that
BgColor1's `power` field drives it — so that write was reverted while BlinkLight's was kept
(there the shader `LightBlinkBlend` is named for the track and pairs `_BlinkLightColor` with
`_ColorPower`, which is a much tighter fit).
Open items and why each is blocked are tracked in `LIVE_TRACKS.md` → 「已知未解问题」.
## Currently Implemented Tracks
| Track | Data class | Notes |
|-------|-----------|-------|
| Camera (pos/lookat/fov/roll/switcher) | existing | fully working |
| CharaMotionSequence | existing | |
| Facial / LipSync / FormationOffset | existing | |
| GlobalLight (48) | existing | sets rim light shader props on characters |
| BgColor1 | existing | **two branches.** Groups named `CharaCenter/CharaLeft/CharaRight/CharaColor` (`LiveTimelineControl.CharaBgColorNames`) → character toon props (`_CharaColor`, `_ToonDarkColor`, …). Every other group name → stage renderers, resolved by walking the whole stage hierarchy for same-named Transforms (`Director.ResolveStageTargets`), writing **`_MulColor0`** via `MaterialPropertyBlock`. |
| BgColor2 | existing | sets `_AmbientColor` on stage renderers via `Lerp(color1, color2, value)` |
| Transform / Object | existing | handled by `StageController.cs` |
| Effect (60) | `LiveTimelineEffectData` | loads prefab from `3d/effect/live/pfb_{name}` |
| GlobalFog (49) | `LiveTimelineGlobalFogData` | sets `RenderSettings.fog*` |
| Spotlight3d (68) | `LiveTimelineSpotlight3dData` | looks up `keyData.assetName` in StageObjectMap |
| UVScrollLight (46) | `LiveTimelineUVScrollLightData` | sets texture UV on stage materials |
| VolumeLight (37) | `LiveTimelineVolumeLightData` | data deserialized, no visual (component absent) |
| LightShafts (50) | `LiveTimelineLightShaftsData` | data deserialized, no visual (component absent) |
| Particle (41) | `LiveTimelineParticleData` | sets ParticleSystem.emission.rateOverTime |
| ParticleGroup (42) | `LiveTimelineParticleGroupData` | sets FlickerLightRate |
| ChromaticAberration (73) | `LiveTimelineChromaticAberrationData` | URP `ChromaticAberration.intensity` ← `power`;per-channel offset 无法映射 |
| HdrBloom (38) | `LiveTimelineHdrBloomData` | **no handler, deliberately** — 0/58 songs carry data (`hdrBloomKeys` empty in every scan and in the song-1177 dump), and the field→URP-`Bloom` mapping was never verifiable. Data layer (data class, worksheet field, event) is kept; the Director handler and the `Bloom` volume override were removed 2026-08-07. |
| ColorCorrection (61) | `LiveTimelineColorCorrectionData` | URP `ColorAdjustments.saturation` + `ColorCurves` RGB;depth/blend curve 无 URP 对应 |
| BlinkLight | `LiveTimelineBlinkLightData` | SetActive + writes `_BlinkLightColor`/`_ColorPower` on the group's renderers (56/58 songs). **Biggest lighting payload by far** — 全语料 19420 keys / 57 songs, and over half are named `*_wash_*` (`wash_truss_a` 147, `wash_truss_b` 147, `wash_ground_a` 51, …). Palette slot = the `lightNNN_`/`alphaNNN_` prefix of the renderer or its nearest ancestor; renderers with no prefix are left to their real owner (BgColor1) when the group has slotted ones. `color1Array` / `LightBlendMode` / `isReverseHueArray` still unused. |
| WashLight | `LiveTimelineWashLightData` | SetActive only (5/58 songs). Low value: real "wash light" output comes from the BlinkLight `*_wash_*` groups above, not this track — song 1177 has just 1 group / 11 keys here. |
| Laser | `LiveTimelineLaserData` | SetActive + position/rotation/scale — blink/raycast not implemented (6/58 songs) |
## Track Coverage (from 58-song scan)
**The pre-2026-08-04 scan data in `LIVE_TRACKS.md` was wrong** and has been re-measured with `tools/`. Two systematic errors: a batch of tracks marked "WorkSheet 无 X 字段" do have the field (`MobControlKeys`, `CyalumeControlKeys`, `nodeScaleList`, `sweatLocatorList`, `monitorCameraPos/LookAtKeys`, `facialNoiseKeys`, `charaMotionNoiseKeys`, …), and a batch marked "全 0 keyframe 空占位" carry thousands of keys (`postFilmKeys`/`postFilm2Keys`/`postFilm3Keys` ≈20 200 keys over 59/59 songs, `radialBlurKeys`, `tiltShiftKeys`, `charaFootLightKeys`, …). Rows tagged ✅实测 are trustworthy; untagged rows are still old data. **Re-verify with `tools/` before acting on any untagged row.**
Coverage numbers measure **what exists in the bundles**, not what the C# consumes — the two diverge. When a track looks under-powered, check the dispatcher in `AlterUpdate_*` for filters before assuming it's unimplemented (BgColor1 was dropping ~92% of its keys that way).
**Measuring what a song actually carries**: `LiveTimelineWorksheetDiag.Dump()` is called from `Director.InitializeTimeline()` and logs, per worksheet, every track field with its group names and key counts. Confirmed on song 1177: `worksheetList.Count == 1`, `SheetType == MainLive`, so reading `worksheetList[0]` loses nothing.
+3 -3
View File
@@ -979,11 +979,11 @@ PlayerSettings:
apiCompatibilityLevel: 6
activeInputHandler: 0
windowsGamepadBackendHint: 0
cloudProjectId: df2b6b43-4005-4a11-a458-1d7d5d5fe6e8
cloudProjectId:
framebufferDepthMemorylessMode: 0
qualitySettingsNames: []
projectName: viewer
organizationId: hongyiw689
projectName:
organizationId:
cloudEnabled: 0
legacyClampBlendShapeWeights: 0
hmiLoadingImage: {fileID: 0}
@@ -10,6 +10,8 @@ UnityConnectSettings:
m_EventUrl: https://cdp.cloud.unity3d.com/v1/events
m_ConfigUrl: https://config.uca.cloud.unity3d.com
m_DashboardUrl: https://dashboard.unity3d.com
m_CNEventUrl: https://cdp.cloud.unity.cn/v1/events
m_CNConfigUrl: https://cdp.cloud.unity.cn/config
m_TestInitMode: 0
CrashReportingSettings:
m_EventUrl: https://perf-events.cloud.unity3d.com
@@ -23,6 +25,7 @@ UnityConnectSettings:
m_Enabled: 0
m_TestMode: 0
m_InitializeOnStartup: 1
m_PackageRequiringCoreStatsPresent: 0
UnityAdsSettings:
m_Enabled: 0
m_InitializeOnStartup: 1
+4 -2
View File
@@ -40,7 +40,7 @@ Currently only the default work mode is supported - you need to download assets
- 2A\\...
- 2B\\...
- ...\\...
3. Download the most recent UmaViewer.zip file from [Releases](https://github.com/zuoy865-stack/UmaViewer/releases) tab.
3. Download the most recent UmaViewer.zip file from [Releases](https://github.com/0xcjy/UmaViewer/releases) tab.
4. Extract the archive anywhere, can be extracted over previous version.
5. Run the UmaViewer.exe.
6. UmaViewer will try to automatically detect the game data folder.
@@ -57,7 +57,9 @@ Currently only the default work mode is supported - you need to download assets
PMX exporter maintainers should also read [PMX Export Standard and Postmortem](docs/pmx-export-standard-and-postmortem.md).
Live restoration maintainers should read [2026-10-01 improvement summary and publication boundaries](docs/IMPROVEMENTS_20261001.md). This source snapshot does not establish full visual parity and excludes local keys, extracted game assets, authorization audio payloads, and the native CySpring plugin; these dependencies must be supplied separately.
Live restoration maintainers should read [2026-10-01 improvement summary and publication boundaries](docs/IMPROVEMENTS_20261001.md). This source snapshot does not establish full visual parity and excludes local keys, extracted game assets, authorization audio payloads, and the native CySpring plugin. Current runtime prerequisites are listed below.
The current source includes runtime graphics settings and live-selection updates; it is not a claim of complete rendering parity. Running the viewer requires your own full game data and authorized keys. Supply `DBBaseKeyText`, `DBKeyText`, `GlobalDBKeyText`, `ABKeyText`, and `AudioKeyText` in the local `Config.json` next to the player, then restart. Key fields contain hexadecimal text without a `0x` prefix; `AudioKeyText` is a nonzero key of at most 16 hex digits. Native physics requires your own authorized matching `CySpringPlugin.dll` (for Windows x64 players, in `UmaViewer_Data/Plugins/x86_64`); it is not distributed here. Excluded `cri_auth` and `sound_proj.acf` payloads are not required by the current source's audio decoder. No keys or local configuration are distributed. See [current publication manifest](docs/PUBLICATION_MANIFEST_20261002.json) for exact source hashes and exclusions.
-33
View File
@@ -1,33 +0,0 @@
# UmaViewer Live 还原交接(2026-09-25)
## 首要问题
工作区为 `D:\Projects\UmaTools\UmaViewer-master7`,目标是还原已编译的 `D:\Projects\UmaTools\UmaViewer` 的完整 Live 画面。用户指出:二进制版加载 Live 时进度数字为数千级,master7 为两位数;此前长期修后处理却没有明显画质改进,并且部分画面过亮。**下一步先对齐资源收集、加载和进度计数口径,再判断渲染链是否需要修复。**
这两个数字目前来自用户目测,尚无同条件进度日志、对应的二进制计数函数或两边完整资源清单。不能直接断言 master7 少加载数千项,也不能排除缺资源;绝不可只增大 UI 的计数来掩盖差异。
## 已核实的 master7 链路
- `Assets/Scripts/UmaViewerBuilder.cs:840`:`LoadLive` 经 `Director.GetLivePreloadEntries`、`UmaAssetManager.PreLoadAndRun`,再切换 `LiveScene`、`Director.Initialize`、`LoadLiveUma`、初始化时间轴与音乐。
- `Assets/Scripts/umamusume/Gallop/Live/Director.cs:731`:预载根为语音、Cutt、歌曲 part 和可选的 `3d/env/live/live{BackGroundId}/` 下舞台 bundle,最后按名称去重。`Director.cs:787` 有舞台依赖的同步兜底。这不是完整的角色、动作、特效资产清单。
- `Assets/Scripts/UmaAssetManager.cs:103-147`:根条目去重、展开依赖。Standalone 模式下 `UmaViewerDownload.cs:87-105` 的 `DownLoading(x/y)` 只统计本机缺失的展开条目;本机都有文件时该阶段不显示。之后对每个根执行 `SearchAB`,`Loading(x/y)` 的 `y=loadItems.Count`,可含重复的共享依赖。每次 `AcquireOne` 返回后即递增,**不表示成功打开了 y 个唯一 bundle**:`UmaAssetManager.cs:193-245` 有句柄复用、文件缺失等路径。`UmaSceneController.cs:73-91` 原样显示数字。
- `UmaAssetManager.cs:150` 的 `LoadAssetBundle` 是上述进度回调之外的按需入口。预载结束后 `UmaViewerBuilder.cs:102` 加载角色;`LiveTimelineControl.cs:355` 加载动作;`StageController.cs:284`、`LiveFlashController.cs:650`、`StageLensFlareDriver.cs:237`、`MonitorUvMovieProvider.cs:1741`、`CyalumePlaybackProvider.cs:377` 等有其它加载路径。`UmaViewerMain.cs:77` 另有初始化界面固定 10 步进度,不能和 Live 进度混同。
- master5 的旧预载流程更窄,不能认为它是完整正确的范本;master7 当前目录无 Git 元数据,避免覆盖式拷贝。
## 二进制逆向的起点
- `D:\Projects\UmaTools\UmaViewer\GameAssembly.dll` 与 `UmaViewer_Data\il2cpp_data\Metadata\global-metadata.dat`。磁盘上的 metadata 只有 **21 字节**;master5 的 `tmp/global-metadata.runtime.dat`、`tmp/render-analysis.txt`、`tmp/render-call-map.txt`、`tmp/render-disassembly.txt`、`tmp/render-pipeline-api.txt` 为已有线索。详情见 `docs/LIVE_RENDER_RESTORATION.md:6-11`。本地 Cpp2IL、Il2CppDumper、Il2CppInspector、IDA 可用;此前的 RVA/Shader 研究**没有**建立二进制 Live 资源图和进度计数链。
- 核对正在对比的 exe/DLL 身份与哈希;沿进度 UI 调用、回调源、Live 资源集合构造、依赖展开、资产实际打开和角色/舞台/时间轴阶段建立调用链。函数名相似不等于行为相同;必要时用受控运行日志验证静态推断。不要读取或输出账号、令牌及 `Config.json` 内容。
## 渲染状态与约束
- `docs/LIVE_RENDER_RESTORATION.md` 详列 Bloom/柔光、三层 PostFilm、径向模糊、简单颜色曲线、景深的证据、改动和隔离 GPU 回归。2026-09-25 的主相机检查未发现明确的第二次 Bloom 合成,但不排除多相机、真实帧 RT 交接、参数或素材差异引起过亮。径向模糊时间轴 bit17/bit18 矩形标志未确认。
- `tmp/dof-focus-test-project` 只含最小 Shader 测试素材;GPU PASS 不是全场景 Live 画质对齐。**物理和用户认可的景深算法不要改;不要凭截图盲调后处理强度。**不要关闭或重启用户主 Unity Editor(此前 PID 15476;操作前重查),不要同时启动两个同一隔离测试项目。
- 真实游戏参考是 `D:\Projects\UmaTools\UmaViewer-master5\captures\reference`,不是 master5 的输出。`live1176-content-aligned-20260912/manifest.json` 有歌曲 1176、舞台 10148、14 角色槽、60 fps、1920x1080,优先同条件检查 308、868、3848 帧。完整 Live 对齐截图**尚未完成**。
## 下一阶段的验收
1. 在相同歌曲、舞台、角色、资源库和工作模式下记录两程序进度文字、阶段、最大值;给出二进制计数来源及两边**同口径**的数字定义。
2. master7 增加可开关的只读诊断:预载根数、去重与含重复的依赖请求数、本地缺文件数、实际打开的唯一 bundle、句柄复用、失败和缺依赖;分阶段记录实际 `LoadAsset`/`LoadAllAssets` 请求及成功项。日志用规范名和阶段,不泄露配置/私有路径;`GetAllAssetNames` 的潜在资产数不可冒充实际加载数。
3. 逆向并对照二进制的资源收集和依赖图,明确列出多出/缺少的模型、动作、舞台、灯光/特效、屏幕素材、Shader/纹理,指出可见画面影响。静态无法确认的项目标为未知。
4. 只修有明确证据的缺项;运行 `tools/check_live_compile.ps1` 和隔离 GPU 回归。最后用**完整素材**对齐同一帧、机位及参数,报告资源差异、画面差异和过亮帧结论。若不能运行全场景,明确承认限制,不声称已经完成还原。
File diff suppressed because it is too large Load Diff
-149
View File
@@ -1,149 +0,0 @@
# PMX 导出姿势与 IK 修复实施计划
## 已确认目标
- PMX 导出前固定回到角色初始化姿势,并将左右上臂分别旋转 `-38.5°`、`+38.5°`,生成与历史 VMD 导出一致的 MMD 默认 A-pose。
- 导出期间冻结 Animator、眼动和动态骨,保证顶点烘焙与骨骼位置来自同一参考姿势。
- 无论导出成功或异常,都恢复角色 Transform、表情权重、Animator、眼动和物理状态。
- 按 PMX 文件原始语义写入 IK 角度限制,使用未经尺寸缩放和坐标轴翻转的弧度,并逐轴规范化上下限。
## 实施范围
1. 由角色导出状态快照辅助类冻结状态、应用固定 A-pose,并在结束后完整恢复。
2. PMX 与 VMD 使用同一组 `38.5°` 手臂参考旋转。
3. PMX Writer 对 IK 角度执行有限值校验和端点排序后,以原始弧度直接写入。
4. PMX Reader 以无尺寸倍率、无坐标轴翻转方式读取 IK 弧度,并对异常文件重新排序。
5. 骨架导出前校验 IK 索引及角度区间,拒绝 NaN、Infinity 和倒置区间。
## 验证标准
- `dotnet build umamusume.csproj -nologo` 构建无错误。
- PMX 导出路径不调用 Animator `Rebind()`,而是明确应用固定 MMD A-pose。
- 膝 IK 写入 PMX 并回读后均为约 `[-π, -0.0087]`;MMD Skin/Saba 转换到求解器后为约 `[0.0087, π]`。
- 导出成功和异常路径都能恢复原动作、表情、眼动和物理状态。
- 最终在 MMD Skin 中实机确认导入不崩溃、双臂姿势正确且腿 IK 弯曲方向正常。
- 使用问题动作和正常动作分别导出,并在 Blender 中确认基础姿势不受预览动作影响。
## 执行状态
- [x] 完成导出状态冻结、MMD 默认 A-pose 应用及异常路径恢复。
- [x] 完成标准骨架、腿 IK 和 IK 原始弧度读写修复。
- [x] 完成项目构建、差异检查和膝 IK 二进制写入验证。
- [x] 在 MMD Skin 中实机确认导入、A-pose、膝盖弯曲方向及导出后状态恢复。
- [x] 使用问题动作和正常动作导出,并在 Blender 中确认两份 PMX 的基础姿势一致。
修复复盘和长期维护规则见 `docs/pmx-export-standard-and-postmortem.md`。
---
# PMX/MMD 原生物理导出实施计划(网络资料修订版,待批准)
> 目标是生成符合 PMX 2.x 语义、可由 MMD 标准运行时直接消费的物理数据。MMDSkin 不负责自动补充阻尼追踪;此前“只导出骨骼链”的兼容方案作废,也不会原样恢复已经出现卷曲和拉扯的旧刚体实现。
## 已确认根因
`Assets/Scripts/Exporters/ModelExporter.cs` 当前在构建 PMX 模型时无条件写入空的 `Rigidbodies` 和 `Joints` 数组。因此导出文件虽然包含网格、骨骼和表情,却没有任何 PMX 动力学数据;预览中由 CySpring 驱动的头发、裙摆、耳朵和尾巴不会被带入导出结果。
截图中的 Blender 约束 `mmd_additional_rotation`、目标骨 `_shadow_*` 是 mmd_tools 对 PMX 付与旋转字段的还原。付与旋转只表达骨骼之间的旋转继承,不提供时间延迟、惯性、重力或回弹,不能替代刚体和 Joint。
## 实现目标与边界
- 按 MMD 的三层语义导出:骨骼变形顺序、明确存在的付与旋转关系、刚体与六自由度弹簧 Joint。
- 第一阶段只覆盖由 `CySpringDataContainer.springParam` 明确标识、拓扑可判定为单根串联链的头发、耳朵和尾巴。
- 裙摆不是普通串联链:按 MMD 常用做法,需要纵向动态刚体链、同层横向 Joint 和薄盒体共同组成网格,因此独立放在第二阶段,不能套用头发胶囊链。
- CySpring 只用于识别动态链及提供参数参考,不假定其参数与 MMD Bullet 一一等价;首版采用集中定义、可校准的保守 MMD 预设。
- 第一阶段不导出复杂身体碰撞体和环境平面,不承诺逐帧复刻游戏内 CySpring、风场或裙摆专用求解结果。
- 不为所有 `Sp_*` 父子骨自动添加付与旋转。只有存在明确 MMD 继承语义时才写入 `AppendRotate`,避免动画层级和物理层级产生双重旋转。
## 影响范围
1. `Assets/Scripts/Exporters/PMXPhysicsExporter.cs`(新增)
收集 CySpring 骨骼链,按 PMX 语义建立刚体、Joint、碰撞过滤和参数校验;坐标与角度换算集中在此处。
2. `Assets/Scripts/Exporters/ModelExporter.cs`
在骨骼索引建立完成后调用物理导出器,替换当前的空数组赋值。
3. `Assets/Scripts/Exporters/PMXBoneExporter.cs`
为参与物理的骨骼设置符合 MMD 更新顺序的 `PostPhysics` 与 `TransformLevel`;保留已经加入的标准 `両目` 控制骨。
4. `Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Writer/PMXWriter.cs`
保留刚体碰撞组单字节修复,并严格区分空间坐标、尺寸和弧度字段的写入规则。
5. `Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/PMXReader.cs`
对称修正 Joint 角度字段读取,保证 PMX 往返后数值与单位一致。
6. `Assets/Scripts/Exporters/PMXPhysicsExporterTests.cs`(新增)
覆盖链提取、骨骼缺失、非法浮点、索引关联、刚体类型、碰撞掩码、坐标方向和弧度区间。
## 参数映射方案
| CySpring 数据 | PMX 导出策略 |
| --- | --- |
| `springParam` 的根/子骨骼 | 识别连续动态链,只接受已存在于 PMX 骨骼索引中的节点 |
| 骨骼位置与子骨方向 | 计算胶囊中心、长度及朝向;末端缺少子骨时使用可验证的链段回退规则 |
| `collisionRadius` | 作为半径参考并进行有限值和骨长比例钳制,不直接无界写入 |
| `_stiffnessForce` | 仅作为预设档位参考,转换后的旋转弹簧系数集中定义并可调 |
| `_dragForce` | 仅作为阻尼档位参考,分别映射到平移阻尼和旋转阻尼并限制范围 |
| `_gravity` | 不直接写入刚体;PMX 没有逐刚体重力字段,只参与预设选择或记录诊断 |
| `_isLimit` | 作为是否启用保守旋转限制的参考;首版不猜测不存在的逐轴 CySpring 限制 |
| `collisionNameList` | 第一阶段只用于诊断;第二阶段加入身体碰撞体后再映射跨组碰撞关系 |
## 刚体与关节生成规则
1. 根据 `PMXBoneExporter.Result.BoneIndexes` 解析 CySpring 骨骼名并拆分连续链;缺失节点在日志中聚合报告,不能跨过缺失节点强行连接 Joint。
2. 每条链根部使用关联链根父骨的 `Type 0 / 骨骼跟随` 支撑刚体,后续链段使用 `Type 1 / 物理演算` 动态刚体。若父骨已有可复用支撑体则不重复生成,防止初始重叠。`Type 2` 首版禁用,因为它会在 Bullet 求解后额外校正骨骼位置,位移限制不当时容易放大振动。
3. 相邻刚体使用 PMX 2.0 Joint 类型 `0`(Spring 6DOF)连接,Joint 位置放在对应骨骼节点。固定以父级或锚刚体为 A、子动态刚体为 B,作为稳定的写入约定;不假定 A/B 顺序本身提供阻尼语义。
4. 线性链的形状按链段几何选择:有明确长度且适合覆盖细长骨段时使用胶囊,短链段或近球形末端使用球体。胶囊中心位于链段中点,轴由父骨指向子骨;不能稳定定向时回退为球体并记录诊断。
5. 刚体在初始姿势下必须没有会产生排斥的非预期重叠。动态链使用专用碰撞组并关闭组内自碰撞,避免同链及不同发束互相挤压;第一阶段没有身体碰撞体,因此也不伪造跨组碰撞关系。
6. 平移限制默认锁定在 Joint 原点;旋转限制依据链段局部轴开放,不使用统一的三个轴对称小角度。教程表明限制过紧同样会产生边界振动,因此首版采用可校准的中等活动范围,并由阻尼和旋转弹簧负责收敛。
7. 质量从根部向末端递减,末端平移和旋转阻尼逐步增大,以降低长链末端不断累积的运动能量。反弹力和摩擦力默认设为 `0`。具体数值集中在命名预设中,并在 MMDSkin 样本测试后校准,不把教程示例值直接硬编码为规范值。
8. 动态刚体关联的骨骼标记为物理后变形;锚骨及普通动画骨保持物理前变形。实际 `TransformLevel` 依据父子依赖单调设置,避免物理结果被后续动画覆盖。
## 裙摆独立拓扑
1. 只有在 CySpring 数据和骨骼父子关系能稳定识别出“列 × 段”的裙摆网格时才生成裙摆物理;无法判定时跳过并报告,不猜测相邻列。
2. 每列由腰部 `Type 0` 支撑体连接若干 `Type 1` 动态体,刚体使用沿布片切向排列的薄盒体,不使用统一胶囊。
3. 同列上下段用纵向 Joint 控制布料弯曲;同一高度的相邻列用横向 Joint 闭环连接,防止各列像独立帘条一样散开。环的首尾也必须连接。
4. 横向 Joint 允许少量平移和旋转,不能像线性链一样全部锁零;允许量必须按裙摆半径、列数和段数归一化,避免模型尺寸变化后参数失效。
5. 裙摆刚体同组禁碰撞,并依赖横向 Joint 保持整体形状。腿部 `Type 0` 碰撞体及裙摆到腿部的碰撞掩码放在身体碰撞阶段实现。
## 坐标与单位规则
- PMX 位置、刚体尺寸和 Joint 平移量使用与现有顶点/骨骼一致的 Unity 到 MMD 坐标变换及模型倍率。
- 刚体欧拉旋转、Joint 旋转限制和旋转弹簧的轴分量不应用模型尺寸倍率。
- PMX 文件中的旋转和旋转限制统一写为弧度;Reader 回读后必须保持弧度语义,不在底层工具函数中混入 `Rad2Deg` 或空间倍率。
- PMX 刚体尺寸是按形状解释的 `vec3`;球体、盒体、胶囊必须分别构造,不能把同一个三轴值无差别写给所有形状。盒体在 mmd_tools 中还存在 Y/Z 轴交换,往返测试必须覆盖这一点。
- 胶囊方向先由变换后的 MMD 空间链段向量计算,再生成 PMX 欧拉角,避免先算 Unity 欧拉角后简单翻轴造成方向错误。
- 每个旋转轴的下限必须小于等于上限;NaN、Infinity、非法长度和无效索引不得写入文件。
## 验证标准
- 导出无 CySpring 链的模型时,刚体/Joint 数量保持为零且不报错。
- 二进制级检查刚体碰撞组为单字节,Joint 类型为 `0`,所有索引有效,所有旋转字段均为有限弧度值。
- 使用本项目 PMX Reader 回读导出文件,刚体数量、Joint 数量、关联索引、位置、尺寸和旋转限制与写入前一致。
- Blender mmd_tools 能加载并显示正确朝向的球体/胶囊、有效的相邻 Joint;动态骨的“物理后”状态符合预期。
- 每个 Joint 的 A/B 索引均有效,且不能连接两个 `Type 0` 刚体;初始姿势下动态刚体之间没有非预期重叠。
- MMDSkin 能完整解析模型,不进入因 PMX 数据错位导致的失败状态;标准 `両目` 控制骨继续可识别。
- 在 MMDSkin 中以静止、走路和大幅转身动作手工确认:链条有延迟摆动并能收敛,不持续卷曲、不异常拉长、不飞散。
- 第一阶段至少手工验收一份短发、一份长发和一份尾巴模型;裙摆在独立拓扑完成后另行验收。
- 导出后 Unity 预览里的 CySpring、Animator、表情和姿势仍恢复到导出前状态。
- 执行 `dotnet build umamusume.csproj -nologo` 与 `git diff --check`。
## 分阶段交付
第一阶段完成头发、耳朵、尾巴的稳定支撑刚体、动态链刚体、相邻 Joint、组内禁碰撞和物理后变形顺序,不导出裙摆和身体碰撞体。
第二阶段实现可可靠识别的裙摆“列 × 段”网格、薄盒刚体、纵向 Joint 和闭环横向 Joint,先验证裙摆自身能保持连续结构。
第三阶段在读取并核对 CySpring 碰撞数据后,导出身体球体/胶囊 `Type 0` 碰撞体与分组掩码,重点验证头发-身体、尾巴-身体和裙摆-腿部。
第四阶段依据 MMDSkin 手工样本调整集中预设中的刚度、阻尼、质量、旋转限制和碰撞规则;不把单个角色的校准值散落写死到链生成逻辑中。
## 网络资料结论
- [MMD 模型物理设置 Wiki:物理教程](https://w.atwiki.jp/mmdphysics/pages/14.html):确认 `Type 0 → Joint → Type 1` 的基础链、同组禁碰撞、刚体重叠导致持续反弹,以及质量、阻尼、弹簧的调整关系。
- [MMD 模型物理设置 Wiki:刚体与 Joint 构成元素](https://w.atwiki.jp/mmdphysics/pages/16.html):确认三种刚体模式、形状用途、Joint 两端必须关联有效刚体,以及 `Type 2` 的额外骨骼位置校正风险。
- [MMD 模型物理设置 Wiki:高级调整](https://w.atwiki.jp/mmdphysics/pages/15.html):确认头发末端应减小质量并提高阻尼;裙摆需要薄盒刚体、纵向链和同层横向 Joint,且同组自碰撞通常应关闭。
- [MMD 物理设置 Joint 教程](https://tsuki-gummd.hatenablog.com/entry/2022/08/15/210000):确认裙摆纵向 Joint 控制弯曲、横向 Joint 控制横向伸展,参数需要随列数、段数和部位变化。
- [MMD 刚体设置教程](https://tsuki-gummd.hatenablog.com/entry/2024/02/01/211802):确认服装摩擦通常设为零、长链质量与阻尼要分段变化,碰撞体过多会增加失稳风险。
- [PMX 2.0/2.1 格式说明](https://gist.github.com/felixjones/f8a06bd48f9da9a4539f):确认刚体字段、碰撞组字节与 16 位掩码、弧度旋转,以及 PMX 2.0 Spring 6DOF Joint 的字段顺序。
- mmd_tools 的 PMX 导入/导出实现用于交叉核对坐标轴、盒体尺寸和 Joint 上下限转换;PmxTailor 未找到公开源码,不作为规范依据。
## 待确认
批准后先实施第一阶段线性链,以“符合 MMD 原生物理、MMDSkin 可解析、摆动能够稳定收敛”为目标。第一版参数只要求形成可靠基线;每轮构建和静态回读通过后,由用户在 MMDSkin 手工验证,再根据实际表现校准预设。裙摆必须等独立网格拓扑完成后再宣称支持。