Compare commits

..
Author SHA1 Message Date
Jiaqi (0x7c13) Liu 3395a7f7a5 docs: show current pull request build status in badges 2026-11-15 00:01:10 +08:00
Jiaqi Liu 25579c6c0d Replace runtime ResourceViewer with native editor resource browsing (#94) 2026-11-14 23:54:32 +08:00
Jiaqi Liu 4cabbd03a7 Implement native PAL3/PAL3A effects and editing tools (#93)
* Implement original PAL3 effects and editor with formatting checks

* Add native PAL3A effect playback and SPar diagnostics

Enable shared playback for supported PAL3A groups with POL models, model opacity, and explosive geometry. Parse SPar resources for complete dependency diagnostics while retaining whole-group private fallback for pending simulation.

Preserve the last effect position when actors are missing or removed in both games, and keep actor-specific shape changes and private fallback guarded. Expand the editor and viewer to both variants and fix opaque alpha for RGB TGA textures.

Validation: PAL3/PAL3A effect suites 54/54 each; general regressions 278/278 and 295/295. Both-variant formatting and diff checks passed.

* Implement native SPar playback and PAL3A transport effects

Add SPar emitter simulation, native blending and billboard rendering for the
remaining 26 script/scene groups. Restore PAL3A transport geometry and seven
styles in game, the editor and ResourceViewer.

Preserve native live-state initial-frame behavior and mark the runtime UV
table non-serialized. Update the README and add format, playback, geometry
and resource-lifetime regression coverage.

Validation: targeted tests 106/106 for both variants; general regressions
PAL3 293/293 and PAL3A 310/310. Both-variant formatting checks passed.

* Remove prefab effect fallback and simplify effect editing
2026-11-14 22:33:13 +08:00
74 changed files with 4477 additions and 5067 deletions

No files matched your search

+6
View File
@@ -6,6 +6,12 @@ macOS, Linux, and 32-bit/64-bit Windows. The workflows run only on pull requests
New commits cancel superseded runs for the same pull request and workflow.
Successful desktop/Android builds upload artifacts.
The README badges show each workflow's latest pull request build using
`event=pull_request`, with no branch filter. Without the event filter, GitHub's
badges prefer the default branch and can keep showing old push builds after a
workflow switches to PR-only triggers. The badge links filter the build history
to pull requests as well.
The separate `Code style` workflow verifies changed owned C# files with the SDK's
`dotnet format`, using `.editorconfig` and the SDK pinned in `global.json`.
It combines whitespace formatting with pinned StyleCop layout rules SA1107, SA1502,
File diff suppressed because it is too large. Load diff
-539
View File
@@ -1,539 +0,0 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!29 &1
OcclusionCullingSettings:
m_ObjectHideFlags: 0
serializedVersion: 2
m_OcclusionBakeSettings:
smallestOccluder: 5
smallestHole: 0.25
backfaceThreshold: 100
m_SceneGUID: 00000000000000000000000000000000
m_OcclusionCullingData: {fileID: 0}
--- !u!104 &2
RenderSettings:
m_ObjectHideFlags: 0
serializedVersion: 9
m_Fog: 0
m_FogColor: {r: 1, g: 1, b: 1, a: 1}
m_FogMode: 3
m_FogDensity: 0.002
m_LinearFogStart: 0
m_LinearFogEnd: 300
m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1}
m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1}
m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1}
m_AmbientIntensity: 1.3
m_AmbientMode: 0
m_SubtractiveShadowColor: {r: 1, g: 1, b: 1, a: 1}
m_SkyboxMaterial: {fileID: 0}
m_HaloStrength: 0.5
m_FlareStrength: 1
m_FlareFadeSpeed: 3
m_HaloTexture: {fileID: 0}
m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0}
m_DefaultReflectionMode: 0
m_DefaultReflectionResolution: 128
m_ReflectionBounces: 1
m_ReflectionIntensity: 1
m_CustomReflection: {fileID: 0}
m_Sun: {fileID: 0}
m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 1}
m_UseRadianceAmbientProbe: 0
--- !u!157 &3
LightmapSettings:
m_ObjectHideFlags: 0
serializedVersion: 12
m_GIWorkflowMode: 1
m_GISettings:
serializedVersion: 2
m_BounceScale: 1
m_IndirectOutputScale: 1
m_AlbedoBoost: 1
m_EnvironmentLightingMode: 0
m_EnableBakedLightmaps: 1
m_EnableRealtimeLightmaps: 0
m_LightmapEditorSettings:
serializedVersion: 12
m_Resolution: 2
m_BakeResolution: 40
m_AtlasSize: 1024
m_AO: 0
m_AOMaxDistance: 1
m_CompAOExponent: 1
m_CompAOExponentDirect: 0
m_ExtractAmbientOcclusion: 0
m_Padding: 2
m_LightmapParameters: {fileID: 0}
m_LightmapsBakeMode: 1
m_TextureCompression: 1
m_FinalGather: 0
m_FinalGatherFiltering: 1
m_FinalGatherRayCount: 256
m_ReflectionCompression: 2
m_MixedBakeMode: 2
m_BakeBackend: 1
m_PVRSampling: 1
m_PVRDirectSampleCount: 32
m_PVRSampleCount: 500
m_PVRBounces: 2
m_PVREnvironmentSampleCount: 500
m_PVREnvironmentReferencePointCount: 2048
m_PVRFilteringMode: 2
m_PVRDenoiserTypeDirect: 0
m_PVRDenoiserTypeIndirect: 0
m_PVRDenoiserTypeAO: 0
m_PVRFilterTypeDirect: 0
m_PVRFilterTypeIndirect: 0
m_PVRFilterTypeAO: 0
m_PVREnvironmentMIS: 0
m_PVRCulling: 1
m_PVRFilteringGaussRadiusDirect: 1
m_PVRFilteringGaussRadiusIndirect: 5
m_PVRFilteringGaussRadiusAO: 2
m_PVRFilteringAtrousPositionSigmaDirect: 0.5
m_PVRFilteringAtrousPositionSigmaIndirect: 2
m_PVRFilteringAtrousPositionSigmaAO: 1
m_ExportTrainingData: 0
m_TrainingDataDestination: TrainingData
m_LightProbeSampleCountMultiplier: 4
m_LightingDataAsset: {fileID: 112000000, guid: c9e1768594f6afd479e0380c47ec2784, type: 2}
m_LightingSettings: {fileID: 4890085278179872738, guid: c3e8b810b348ed54ba97c7a4ee44d9eb, type: 2}
--- !u!196 &4
NavMeshSettings:
serializedVersion: 2
m_ObjectHideFlags: 0
m_BuildSettings:
serializedVersion: 2
agentTypeID: 0
agentRadius: 0.5
agentHeight: 2
agentSlope: 45
agentClimb: 0.4
ledgeDropHeight: 0
maxJumpAcrossDistance: 0
minRegionArea: 2
manualCellSize: 0
cellSize: 0.16666667
manualTileSize: 0
tileSize: 256
accuratePlacement: 0
maxJobWorkers: 0
preserveTilesOutsideBounds: 0
debug:
m_Flags: 0
m_NavMeshData: {fileID: 0}
--- !u!1 &806768031
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 806768034}
- component: {fileID: 806768033}
- component: {fileID: 806768032}
m_Layer: 0
m_Name: EventSystem
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!114 &806768032
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 806768031}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 01614664b831546d2ae94a42149d80ac, type: 3}
m_Name:
m_EditorClassIdentifier:
m_MoveRepeatDelay: 0.5
m_MoveRepeatRate: 0.1
m_XRTrackingOrigin: {fileID: 0}
m_ActionsAsset: {fileID: -944628639613478452, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_PointAction: {fileID: -1654692200621890270, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_MoveAction: {fileID: -8784545083839296357, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_SubmitAction: {fileID: 392368643174621059, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_CancelAction: {fileID: 7727032971491509709, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_LeftClickAction: {fileID: 3001919216989983466, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_MiddleClickAction: {fileID: -2185481485913320682, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_RightClickAction: {fileID: -4090225696740746782, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_ScrollWheelAction: {fileID: 6240969308177333660, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_TrackedDevicePositionAction: {fileID: 6564999863303420839, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_TrackedDeviceOrientationAction: {fileID: 7970375526676320489, guid: ca9f5fa95ffab41fb9a615ab714db018, type: 3}
m_DeselectOnBackgroundClick: 1
m_PointerBehavior: 0
--- !u!114 &806768033
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 806768031}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 76c392e42b5098c458856cdf6ecaaaa1, type: 3}
m_Name:
m_EditorClassIdentifier:
m_FirstSelected: {fileID: 0}
m_sendNavigationEvents: 1
m_DragThreshold: 10
--- !u!4 &806768034
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 806768031}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1001 &2755888771526933938
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 2675203688159455099, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchorMax.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2675203688159455099, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchorMin.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2675203688159455099, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_SizeDelta.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2675203688159455099, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_SizeDelta.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2675203688159455099, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchoredPosition.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2675203688159455099, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchoredPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2675384619832620949, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchorMax.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2675384619832620949, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchorMin.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2675384619832620949, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_SizeDelta.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2675384619832620949, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_SizeDelta.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2675384619832620949, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchoredPosition.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2675384619832620949, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchoredPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773260843717, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_Name
value: IngameDebugConsole
objectReference: {fileID: 0}
- target: {fileID: 2755888773280878983, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchoredPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773280971043, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchorMax.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773280971043, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchorMin.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773280971043, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_SizeDelta.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773280971043, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_SizeDelta.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773280971043, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchoredPosition.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773280971043, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchoredPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773280980657, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchorMax.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773280980657, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchorMin.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773280980657, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_SizeDelta.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773280980657, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_SizeDelta.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773280980657, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchoredPosition.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773280980657, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchoredPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281030725, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchorMax.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281030725, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchorMin.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281030725, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_SizeDelta.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281030725, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_SizeDelta.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281030725, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchoredPosition.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281030725, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchoredPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281033885, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchorMax.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281033885, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchorMax.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_Pivot.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_Pivot.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_RootOrder
value: 1
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchorMax.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchorMax.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchorMin.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchorMin.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_SizeDelta.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_SizeDelta.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_LocalPosition.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_LocalPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_LocalPosition.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_LocalRotation.w
value: 1
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_LocalRotation.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_LocalRotation.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_LocalRotation.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchoredPosition.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchoredPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281068093, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281069695, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchorMax.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281069695, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchorMin.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281069695, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_SizeDelta.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281069695, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_SizeDelta.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281069695, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchoredPosition.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281069695, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchoredPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281072733, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchorMax.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281072733, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchorMin.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281072733, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_SizeDelta.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281072733, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_SizeDelta.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281072733, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchoredPosition.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 2755888773281072733, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
propertyPath: m_AnchoredPosition.y
value: 0
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: 3ef1d32c83f86744286e2067bc5f73e4, type: 3}
--- !u!1001 &6005496283450936117
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 6005496284174148228, guid: 23121fd589eec48458b9201ba9cfc3f7, type: 3}
propertyPath: startingComponent
value:
objectReference: {fileID: 4717529239480754811, guid: e65c4b938f18e6c4a86dc379157fac65, type: 3}
- target: {fileID: 6005496284174148229, guid: 23121fd589eec48458b9201ba9cfc3f7, type: 3}
propertyPath: m_Name
value: Resource Initializer
objectReference: {fileID: 0}
- target: {fileID: 6005496284174148231, guid: 23121fd589eec48458b9201ba9cfc3f7, type: 3}
propertyPath: m_RootOrder
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6005496284174148231, guid: 23121fd589eec48458b9201ba9cfc3f7, type: 3}
propertyPath: m_LocalPosition.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6005496284174148231, guid: 23121fd589eec48458b9201ba9cfc3f7, type: 3}
propertyPath: m_LocalPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6005496284174148231, guid: 23121fd589eec48458b9201ba9cfc3f7, type: 3}
propertyPath: m_LocalPosition.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6005496284174148231, guid: 23121fd589eec48458b9201ba9cfc3f7, type: 3}
propertyPath: m_LocalRotation.w
value: 1
objectReference: {fileID: 0}
- target: {fileID: 6005496284174148231, guid: 23121fd589eec48458b9201ba9cfc3f7, type: 3}
propertyPath: m_LocalRotation.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6005496284174148231, guid: 23121fd589eec48458b9201ba9cfc3f7, type: 3}
propertyPath: m_LocalRotation.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6005496284174148231, guid: 23121fd589eec48458b9201ba9cfc3f7, type: 3}
propertyPath: m_LocalRotation.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6005496284174148231, guid: 23121fd589eec48458b9201ba9cfc3f7, type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6005496284174148231, guid: 23121fd589eec48458b9201ba9cfc3f7, type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 6005496284174148231, guid: 23121fd589eec48458b9201ba9cfc3f7, type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: 23121fd589eec48458b9201ba9cfc3f7, type: 3}
+16 -1
View File
@@ -52,14 +52,18 @@ namespace Editor
private float? _pendingSeek;
private double _seekAfter;
#if PAL3
[MenuItem("PAL3/Effect Editor")]
#endif
public static void Open()
{
var window = GetWindow<EffectEditor>("Effects");
window.ChangeVariant(false);
}
#if PAL3A
[MenuItem("PAL3A/Effect Editor")]
#endif
public static void OpenPal3A()
{
var window = GetWindow<EffectEditor>("Effects");
@@ -68,7 +72,18 @@ namespace Editor
private void ChangeVariant(bool pal3a)
{
if (_pal3a == pal3a || !CanReplaceEdits())
if (_pal3a == pal3a)
{
string path = EditorPrefs.GetString($"{Variant}.OriginalEffect.DataPath", _dataPath);
int codepage = EditorPrefs.GetInt($"{Variant}.OriginalEffect.Codepage", 936) == 950 ? 950 : 936;
if (path == _dataPath && codepage == _codepage || !CanReplaceEdits())
return;
LoadOverrides(Resources.Load<OriginalEffectOverrides>($"Effects/{Variant}Overrides"));
LoadPreferences();
LoadData();
return;
}
if (!CanReplaceEdits())
return;
_pal3a = pal3a;
_id = pal3a ? 160 : 98;
@@ -1,5 +1,6 @@
fileFormatVersion: 2
guid: 9fc0d4010bbf28b4594072e72b8655ab
guid: 7f8f503fe8584c3e887350c2988f8a22
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
@@ -0,0 +1,7 @@
{
"name": "Pal3.ResourceBrowser.Editor",
"rootNamespace": "Pal3.ResourceBrowser",
"references": ["Pal3.Core", "Pal3.Game", "Engine", "Unity.RenderPipelines.Core.Runtime", "Unity.RenderPipelines.Universal.Runtime"],
"includePlatforms": ["Editor"],
"autoReferenced": true
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7f7e3be4da704be9bacbd3af0989bb5b
@@ -0,0 +1,565 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;
public sealed partial class ResourceBrowserWindow : EditorWindow
{
#if PAL3A
public const string Variant = "PAL3A";
#else
public const string Variant = "PAL3";
#endif
[SerializeField] private string _dataPath, _query = "";
[SerializeField] private int _codepage = 936, _categoryIndex, _sourceIndex;
private ResourceCatalog _catalog;
private float DetailWidth => position.width - Mathf.Clamp(position.width * 0.34f, 240, 460) - 12;
private bool SelectedCatalogMatches => _catalog != null && (_textDraft == null || _textDraft.CanReadFrom(_catalog.Root));
private Task<ResourceCatalog> _scan;
private CancellationTokenSource _scanCancellation;
private volatile string _scanStatus;
private readonly List<ResourceEntry> _visible = new();
private string[] _sources = { "All" };
private ResourceEntry _selected;
private byte[] _bytes;
private ResourceTexturePreview _texture;
private ResourceMediaPreview _media;
private ResourceExportMode _exportMode;
private string _selectedMetadata;
private string _error, _status;
private Vector2 _listScroll, _detailScroll;
private int _hexPage;
private string _hex;
private Task<string> _export;
private CancellationTokenSource _exportCancellation;
private volatile string _exportStatus;
[MenuItem(Variant + "/Resource Browser", priority = 30)]
public static void Open() => GetWindow<ResourceBrowserWindow>("Resources");
private void OnEnable()
{
minSize = new Vector2(900, 580);
wantsMouseMove = true;
_dataPath = EditorPrefs.GetString(Variant + ".ResourceBrowser.Path",
Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", Variant)));
_codepage = EditorPrefs.GetInt(Variant + ".ResourceBrowser.Codepage", 936);
saveChangesMessage = "Save the edited resource text as a new file before closing?";
ResourceMediaPreview.CleanupStaleTemporaryFiles();
Undo.undoRedoPerformed += UpdateTextDirty;
EditorApplication.update += Tick;
EditorApplication.playModeStateChanged += OnPlayModeChanged;
if (Directory.Exists(_dataPath))
StartScan(restoreDraft: true);
RestoreTextDraft();
}
private void OnDisable()
{
Undo.undoRedoPerformed -= UpdateTextDirty;
EditorApplication.update -= Tick;
EditorApplication.playModeStateChanged -= OnPlayModeChanged;
CancelScan();
_exportCancellation?.Cancel();
_exportCancellation?.Dispose();
_exportCancellation = null;
if (_export != null)
_ = _export.ContinueWith(task => { _ = task.Exception; }, TaskScheduler.Default);
_export = null;
ClearSelection();
_catalog?.Dispose();
_catalog = null;
}
private void OnPlayModeChanged(PlayModeStateChange state)
{
if (state is PlayModeStateChange.ExitingEditMode or PlayModeStateChange.ExitingPlayMode)
ClearSelection();
if (state == PlayModeStateChange.EnteredEditMode)
RestoreTextDraft();
Repaint();
}
private void CancelScan()
{
_scanCancellation?.Cancel();
_scanCancellation?.Dispose();
_scanCancellation = null;
if (_scan != null)
{
_ = _scan.ContinueWith(task =>
{
if (task.Status == TaskStatus.RanToCompletion)
task.Result.Dispose();
_ = task.Exception;
}, TaskScheduler.Default);
_scan = null;
}
}
private void StartScan(bool restoreDraft = false)
{
if (!restoreDraft)
{
if (!CanReplaceSelection())
return;
DestroyTextDraft();
}
CancelScan();
ClearSelection();
_catalog?.Dispose();
_catalog = null;
_visible.Clear();
_error = null;
_status = null;
string path = _dataPath;
int codepage = _codepage;
_scanCancellation = new CancellationTokenSource();
CancellationToken token = _scanCancellation.Token;
_scan = Task.Run(() => ResourceCatalog.Load(path, codepage, Variant, token, message => _scanStatus = message), token);
}
private void Tick()
{
TickModel();
if (_media != null && _media.Tick())
Repaint();
if (_scan is { IsCompleted: true })
{
try
{
_catalog = _scan.GetAwaiter().GetResult();
_sources = new[] { "All" }.Concat(_catalog.Entries.Select(e => e.Source).Distinct().OrderBy(s => s)).ToArray();
_sourceIndex = 0;
EditorPrefs.SetString(Variant + ".ResourceBrowser.Path", _catalog.Root);
EditorPrefs.SetInt(Variant + ".ResourceBrowser.Codepage", _codepage);
Filter();
RestoreTextDraft();
_status = $"{_catalog.Entries.Count:N0} resources indexed";
if (_catalog.Diagnostics.Count > 0)
_error = string.Join("\n", _catalog.Diagnostics);
}
catch (OperationCanceledException) { _status = "Indexing cancelled."; }
catch (Exception ex) { _error = ex.Message; }
_scan = null;
_scanCancellation?.Dispose();
_scanCancellation = null;
Repaint();
}
if (_export is { IsCompleted: true })
{
try
{
_status = _export.GetAwaiter().GetResult();
}
catch (Exception ex) { _error = ex.Message; }
_export = null;
_exportCancellation?.Dispose();
_exportCancellation = null;
Repaint();
}
if (_scan != null || _export != null)
Repaint();
}
private void Filter()
{
_visible.Clear();
_categoryIndex = Mathf.Clamp(_categoryIndex, 0, ResourceFormats.Categories.Length - 1);
_sourceIndex = Mathf.Clamp(_sourceIndex, 0, _sources.Length - 1);
string[] terms = ResourceCatalog.SplitQuery(_query);
if (_catalog != null)
_visible.AddRange(_catalog.Entries.Where(e => ResourceCatalog.Matches(e, terms,
ResourceFormats.Categories[_categoryIndex], _sources[_sourceIndex])));
_listScroll = Vector2.zero;
}
private void OnGUI()
{
int listControl = GUIUtility.GetControlID(FocusType.Keyboard);
HandleListKeys(listControl);
using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar))
{
GUILayout.Label(Variant, EditorStyles.boldLabel, GUILayout.Width(50));
using (new EditorGUI.DisabledScope(_scan != null || _export != null))
{
_dataPath = EditorGUILayout.TextField(_dataPath, EditorStyles.toolbarTextField);
if (GUILayout.Button("Folder…", EditorStyles.toolbarButton, GUILayout.Width(65)))
{
string path = EditorUtility.OpenFolderPanel("Select " + Variant + " game data", _dataPath, "");
if (path.Length > 0)
_dataPath = path;
}
_codepage = EditorGUILayout.Popup(_codepage == 950 ? 1 : 0, new[] { "简体 936", "繁體 950" }, GUILayout.Width(90)) == 0 ? 936 : 950;
if (GUILayout.Button("Index / Reload", EditorStyles.toolbarButton, GUILayout.Width(100)))
StartScan();
}
if (_scan != null && GUILayout.Button("Cancel", EditorStyles.toolbarButton, GUILayout.Width(60)))
{
CancelScan();
_status = "Indexing cancelled.";
}
}
using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar))
{
EditorGUI.BeginChangeCheck();
GUI.SetNextControlName("ResourceSearch");
_query = EditorGUILayout.TextField(_query, EditorStyles.toolbarSearchField);
_categoryIndex = EditorGUILayout.Popup(_categoryIndex, ResourceFormats.Categories, GUILayout.Width(110));
_sourceIndex = EditorGUILayout.Popup(_sourceIndex, _sources, GUILayout.Width(150));
if (EditorGUI.EndChangeCheck())
Filter();
_exportMode = (ResourceExportMode)EditorGUILayout.EnumPopup(_exportMode, EditorStyles.toolbarPopup, GUILayout.Width(75));
using (new EditorGUI.DisabledScope(_visible.Count == 0 || _export != null || _scan != null))
{
if (GUILayout.Button("Export filtered…", EditorStyles.toolbarButton, GUILayout.Width(115)))
ExportFiltered();
}
}
GUILayout.Label($"{_visible.Count:N0} matches · Search: words, -exclude, ext:dds · {_status}", EditorStyles.miniLabel);
if (_scan != null)
EditorGUILayout.HelpBox("Indexing: " + _scanStatus, MessageType.Info);
if (_export != null)
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Label(_exportStatus);
if (GUILayout.Button("Cancel export", GUILayout.Width(110)))
_exportCancellation?.Cancel();
}
}
if (!string.IsNullOrEmpty(_error))
{
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.HelpBox(_error, MessageType.Warning);
if (GUILayout.Button("×", GUILayout.Width(22)))
_error = null;
}
}
using (new EditorGUILayout.HorizontalScope())
{
float width = Mathf.Clamp(position.width * 0.34f, 240, 460);
Rect listRect = GUILayoutUtility.GetRect(width, width, 100, 100000, GUILayout.ExpandHeight(true));
DrawList(listRect, listControl);
using (new EditorGUILayout.VerticalScope(GUILayout.ExpandWidth(true)))
DrawDetail();
}
}
private void DrawList(Rect rect, int listControl)
{
const float rowHeight = 38;
ResourceEntry clicked = null;
_listScroll = GUI.BeginScrollView(rect, _listScroll, new Rect(0, 0, rect.width - 18, _visible.Count * rowHeight));
int first = Mathf.Max(0, (int)(_listScroll.y / rowHeight));
int last = Mathf.Min(_visible.Count, first + Mathf.CeilToInt(rect.height / rowHeight) + 1);
for (int i = first; i < last; i++)
{
ResourceEntry entry = _visible[i];
Rect row = new(0, i * rowHeight, rect.width - 18, rowHeight);
if (entry == _selected)
EditorGUI.DrawRect(row, new Color(0.2f, 0.4f, 0.6f, 0.5f));
GUI.Label(new Rect(row.x + 6, row.y, row.width - 6, 19), entry.Name, EditorStyles.boldLabel);
GUI.Label(new Rect(row.x + 6, row.y + 18, row.width - 6, 18), new GUIContent(entry.Path, entry.Path), EditorStyles.miniLabel);
if (Event.current.type == EventType.MouseDown && row.Contains(Event.current.mousePosition))
{
clicked = entry;
GUIUtility.keyboardControl = listControl;
Event.current.Use();
break;
}
}
GUI.EndScrollView();
if (clicked != null)
{
Select(clicked);
GUIUtility.ExitGUI();
}
}
private void HandleListKeys(int listControl)
{
if (Event.current.type != EventType.KeyDown || Event.current.keyCode is not (KeyCode.UpArrow or KeyCode.DownArrow) ||
GUIUtility.keyboardControl != listControl && GUI.GetNameOfFocusedControl() != "ResourceSearch" || _visible.Count == 0)
return;
const float rowHeight = 38;
int index = Mathf.Clamp(_visible.IndexOf(_selected) + (Event.current.keyCode == KeyCode.DownArrow ? 1 : -1), 0, _visible.Count - 1);
Select(_visible[index]);
float bottom = _listScroll.y + Mathf.Max(100, position.height - 180);
if (index * rowHeight < _listScroll.y)
_listScroll.y = index * rowHeight;
else if ((index + 1) * rowHeight > bottom)
_listScroll.y += (index + 1) * rowHeight - bottom;
Event.current.Use();
GUIUtility.ExitGUI();
}
private void ClearSelection()
{
_media?.Dispose();
_media = null;
_selectedMetadata = null;
ClearModelView();
ClearSceneView();
ClearDataView();
_texture?.Dispose();
_texture = null;
_selected = null;
_bytes = null;
_hex = null;
_hexPage = 0;
_detailScroll = Vector2.zero;
}
private void Select(ResourceEntry entry)
{
if (entry == null || !CanReplaceSelection())
return;
DestroyTextDraft();
ClearSelection();
_selected = entry;
_error = null;
if (EditorApplication.isPlayingOrWillChangePlaymode)
return;
try
{
var sizes = _catalog.GetSizes(entry);
_selectedMetadata = $"{entry.Source} · {sizes.length:N0} bytes" + (entry.IsArchived ? $" · packed {sizes.packedLength:N0} bytes" : "");
if (entry.Category is "Audio" or "Video")
{
_media = new ResourceMediaPreview(_catalog, entry);
return;
}
_bytes = _catalog.Read(entry, entry.Category == "Text" ? 4 * 1024 * 1024 : ResourceCatalog.PreviewByteLimit);
if (entry.Category == "Textures")
_texture = new ResourceTexturePreview(entry, _bytes);
else if (entry.Category == "Models")
LoadModelView(entry);
else if (entry.Category == "Text")
LoadText(entry);
else
_decoded = ResourceFormats.Read(entry, _bytes, _catalog.Codepage);
}
catch (Exception ex)
{
if (_textDraft != null && _textDraft.Text == null)
DestroyTextDraft();
_error = entry.Path + "\n" + ex.Message;
}
Repaint();
}
private void DrawDetail()
{
if (_selected == null)
{
EditorGUILayout.HelpBox("Choose a resource. Models, textures, scripts, scenes and data use dedicated views. No Play Mode is required.", MessageType.Info);
return;
}
GUILayout.Label(_selected.Name, EditorStyles.boldLabel);
if (_selectedMetadata != null)
GUILayout.Label(_selectedMetadata, EditorStyles.miniLabel);
EditorGUILayout.SelectableLabel(_selected.Path, GUILayout.Height(32));
using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar))
{
if (GUILayout.Button("Copy path", EditorStyles.toolbarButton))
EditorGUIUtility.systemCopyBuffer = _selected.Path;
using (new EditorGUI.DisabledScope(!SelectedCatalogMatches))
{
if (GUILayout.Button("Export original…", EditorStyles.toolbarButton))
ExportSelected();
if (_decoded != null)
{
_inspectData = GUILayout.Toggle(_inspectData, "Fields", EditorStyles.toolbarButton);
if (GUILayout.Button("Export JSON…", EditorStyles.toolbarButton))
ExportJson();
}
}
if (_texture != null && GUILayout.Button("Export PNG…", EditorStyles.toolbarButton))
ExportPng();
}
if (EditorApplication.isPlayingOrWillChangePlaymode)
{
EditorGUILayout.HelpBox("Resource previews are available in Edit Mode.", MessageType.Info);
return;
}
if (_inspectData && _decoded != null)
{
_objectView.Draw(_decoded, DetailWidth);
return;
}
if (_selected.Category == "Effects")
{
if (GUILayout.Button("Open Effect Editor"))
OpenEffectEditor();
}
if (_media != null)
_media.Draw();
else if (_texture != null)
{
GUILayout.Label($"{_texture.Texture.width} × {_texture.Texture.height} · {_texture.Texture.format}", EditorStyles.miniLabel);
using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar))
_texture.DrawSettings();
_texture.Draw(GUILayoutUtility.GetRect(100, 10000, 100, 10000, GUILayout.ExpandHeight(true)));
}
else if (_selected.Category == "Models")
DrawModelView();
else if (_decoded is Core.DataReader.Scn.ScnFile scene)
DrawSceneView(scene);
else if (_decoded is Core.DataReader.Nav.NavFile nav)
DrawNavigationView(nav);
else if (_decoded is Core.DataReader.Lgt.LgtFile lights)
DrawLightView(lights);
else if (_decoded is Core.DataReader.Sce.SceFile script)
DrawScriptView(script);
else if (_decoded is Core.DataReader.Gdb.GdbFile database)
DrawDatabaseView(database);
else if (_selected.Category == "Text")
DrawTextView();
else if (_decoded != null)
_objectView.Draw(_decoded, DetailWidth);
else
DrawHex();
}
private void DrawHex()
{
if (_bytes == null)
return;
int pages = Mathf.Max(1, (_bytes.Length + 4095) / 4096);
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Label($"{_bytes.Length:N0} bytes · Hex page", GUILayout.Width(170));
int page = Mathf.Clamp(EditorGUILayout.IntField(_hexPage + 1, GUILayout.Width(60)) - 1, 0, pages - 1);
if (page != _hexPage)
{
_hexPage = page;
_hex = null;
_detailScroll = Vector2.zero;
}
GUILayout.Label($"/ {pages}");
}
if (_hex == null)
{
var text = new StringBuilder();
for (int offset = _hexPage * 4096; offset < Mathf.Min(_bytes.Length, (_hexPage + 1) * 4096); offset += 16)
{
text.Append(offset.ToString("X8")).Append(" ");
for (int i = offset; i < Mathf.Min(offset + 16, _bytes.Length); i++)
text.Append(_bytes[i].ToString("X2")).Append(' ');
text.AppendLine();
}
_hex = text.ToString();
}
_detailScroll = EditorGUILayout.BeginScrollView(_detailScroll);
EditorGUILayout.TextArea(_hex, GUILayout.ExpandWidth(true));
EditorGUILayout.EndScrollView();
}
private void ExportSelected()
{
if (!SelectedCatalogMatches)
return;
string path = EditorUtility.SaveFilePanel("Export original (existing files are kept)", "", _selected.Name, _selected.Extension.TrimStart('.'));
if (path.Length == 0)
return;
try
{
var sizes = _catalog.GetSizes(_selected);
if (_selected.IsArchived && sizes.length + sizes.packedLength > ResourceCatalog.PreviewByteLimit &&
!EditorUtility.DisplayDialog("Large archive resource", $"Extraction needs about {(sizes.length + sizes.packedLength) / 1024 / 1024:N0} MiB of byte buffers. Continue?", "Export", "Cancel"))
return;
_catalog.ExportOriginal(_selected, path);
_status = "Exported " + path;
}
catch (Exception ex) { _error = ex.Message; }
}
private void ExportPng()
{
string path = EditorUtility.SaveFilePanel("Export PNG (existing files are kept)", "", Path.GetFileNameWithoutExtension(_selected.Name), "png");
if (path.Length == 0)
return;
try
{
_catalog.CheckExportDestination(path);
path = ResourceCatalog.ExportPath(Path.GetDirectoryName(path), Path.GetFileName(path));
_texture.SavePng(path);
_status = "Exported " + path;
}
catch (Exception ex) { _error = ex.Message; }
}
private void ExportFiltered()
{
string folder = EditorUtility.OpenFolderPanel("Export filtered resources (existing files are skipped)", "", "");
if (folder.Length == 0)
return;
try
{
_catalog.CheckExportDestination(folder);
}
catch (Exception ex)
{
_error = ex.Message;
return;
}
ResourceExportMode mode = _exportMode;
ResourceEntry[] entries = _visible.Where(entry => ResourceExport.Supports(entry, mode)).ToArray();
ResourceCatalog catalog = _catalog;
_exportCancellation = new CancellationTokenSource();
CancellationToken token = _exportCancellation.Token;
_export = Task.Run(() =>
{
int saved = 0, skipped = 0, failed = 0;
var failures = new List<string>();
foreach (ResourceEntry entry in entries)
{
if (token.IsCancellationRequested)
break;
_exportStatus = $"{saved + skipped + failed + 1:N0}/{entries.Length:N0} · {entry.Path}";
try
{
string destination = ResourceCatalog.ExportPath(folder, entry.Path + ResourceExport.Suffix(mode));
if (File.Exists(destination))
{
skipped++;
continue;
}
var sizes = catalog.GetSizes(entry);
if ((entry.IsArchived || mode != ResourceExportMode.Original) && sizes.length + sizes.packedLength > ResourceCatalog.PreviewByteLimit)
{
skipped++;
continue;
}
ResourceExport.Write(catalog, entry, mode, destination);
saved++;
}
catch (Exception ex)
{
failed++;
if (failures.Count < 10)
failures.Add(entry.Path + ": " + ex.Message);
}
}
return $"{(token.IsCancellationRequested ? "Cancelled. " : "")}Exported {saved:N0}, skipped {skipped:N0}, failed {failed:N0}. Existing files and entries requiring more than 64 MiB to decode are skipped; export large originals individually. " + string.Join(" · ", failures);
});
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 2315df6f0d2b4c42bba962b8c7cfd757
@@ -0,0 +1,275 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Core.DataReader.Cpk;
using Core.FileSystem;
using Game.Effect.Original;
public sealed class ResourceEntry
{
public string Path
{
get;
}
public string PhysicalPath
{
get;
}
public string Extension
{
get;
}
public string Source
{
get;
}
public string Name
{
get;
}
public string Category
{
get;
}
public bool IsArchived => PhysicalPath == null;
public ResourceEntry(string path, string physicalPath = null)
{
Path = path.Replace('/', '\\');
PhysicalPath = physicalPath;
Name = Path[(Path.LastIndexOf('\\') + 1)..];
Extension = System.IO.Path.GetExtension(Name).ToLowerInvariant();
Source = physicalPath == null ? Path.Split('\\')[0] : "Loose files";
Category = ResourceFormats.Category(Extension);
}
}
// No runtime service registrations, Unity objects, or archive preloads. Safe to index off-thread.
public sealed class ResourceCatalog : IDisposable
{
public string Root
{
get;
}
public int Codepage
{
get;
}
public CpkFileSystem FileSystem
{
get;
}
public List<ResourceEntry> Entries { get; } = new();
public List<string> Diagnostics { get; } = new();
private readonly Dictionary<string, ResourceEntry> _lookup = new(StringComparer.OrdinalIgnoreCase);
private ResourceCatalog(string root, int codepage)
{
Root = System.IO.Path.GetFullPath(root);
CheckNoLinks(Root, "The source data folder contains a symbolic link. Select its real target folder to preserve original-data export protection");
Codepage = codepage;
var hash = new Crc32Hash();
hash.Init();
FileSystem = new CpkFileSystem(Root, hash, codepage);
}
public static ResourceCatalog Load(string root, int codepage, string variant,
CancellationToken cancellation = default, Action<string> progress = null)
{
var catalog = new ResourceCatalog(root, codepage);
try
{
var archives = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string file in Directory.EnumerateFiles(catalog.Root, "*", new EnumerationOptions { RecurseSubdirectories = true, AttributesToSkip = FileAttributes.ReparsePoint, IgnoreInaccessible = false }))
{
cancellation.ThrowIfCancellationRequested();
string relative = System.IO.Path.GetRelativePath(catalog.Root, file);
if (string.Equals(System.IO.Path.GetExtension(file), ".cpk", StringComparison.OrdinalIgnoreCase))
{
progress?.Invoke(relative);
if (!archives.Add(System.IO.Path.GetFileName(file)))
throw new InvalidDataException($"Duplicate archive name: {relative}. Select a single game's data directory.");
try
{
catalog.FileSystem.Mount(relative, codepage);
}
catch (Exception ex) { catalog.Diagnostics.Add($"{relative}: {ex.Message}"); }
}
else
catalog.Entries.Add(new ResourceEntry(relative, file));
}
using (var effects = new OriginalEffectResources(catalog.FileSystem, codepage))
{
if (effects.GameVariant != variant)
throw new InvalidDataException($"This folder contains {effects.GameVariant}. Use {variant} data, or Switch Variant in the Unity menu.");
}
progress?.Invoke("Reading archive directory indexes…");
foreach (string path in catalog.FileSystem.Search())
{
cancellation.ThrowIfCancellationRequested();
catalog.Entries.Add(new ResourceEntry(path));
}
catalog.Entries.Sort((a, b) => StringComparer.OrdinalIgnoreCase.Compare(a.Path, b.Path));
foreach (ResourceEntry entry in catalog.Entries)
catalog._lookup.TryAdd(entry.Path, entry);
return catalog;
}
catch
{
catalog.Dispose();
throw;
}
}
public ResourceEntry Find(string path)
{
path = path.Replace('/', '\\');
if (_lookup.TryGetValue(path, out ResourceEntry entry))
return entry;
// PAL3A logical archive names (q02.cpk) resolve through q02_01/02/03.cpk.
int separator = path.IndexOf('\\');
return separator > 0 && path[..separator].EndsWith(".cpk", StringComparison.OrdinalIgnoreCase) && FileSystem.FileExists(path)
? new ResourceEntry(path) : null;
}
public const long PreviewByteLimit = 64 * 1024 * 1024;
public (long length, long packedLength) GetSizes(ResourceEntry entry)
{
if (entry.IsArchived)
return FileSystem.GetFileSizes(entry.Path);
long length = new FileInfo(entry.PhysicalPath).Length;
return (length, 0);
}
public byte[] Read(ResourceEntry entry, long byteLimit = PreviewByteLimit)
{
var sizes = GetSizes(entry);
if (sizes.length > byteLimit || sizes.packedLength > byteLimit)
throw new InvalidDataException($"This resource exceeds the {byteLimit / 1024 / 1024} MiB preview limit. Export the original file instead.");
return entry.IsArchived ? FileSystem.ReadAllBytes(entry.Path) : File.ReadAllBytes(entry.PhysicalPath);
}
public void CheckExportDestination(string destination) => CheckOutsideRoot(Root, destination);
public static void CheckOutsideRoot(string root, string destination)
{
string path = System.IO.Path.GetFullPath(destination);
string source = System.IO.Path.GetFullPath(root).TrimEnd(System.IO.Path.DirectorySeparatorChar);
if (path.Equals(source, StringComparison.OrdinalIgnoreCase) ||
path.StartsWith(source + System.IO.Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
throw new IOException("Choose an output outside the original game data directory.");
}
public void ExportOriginal(ResourceEntry entry, string destination)
{
CheckExportDestination(destination);
// Check symlink ancestors even for a user-selected single-file destination.
destination = ExportPath(System.IO.Path.GetDirectoryName(destination), System.IO.Path.GetFileName(destination));
WriteNewFile(destination, stream =>
{
if (entry.IsArchived)
{
byte[] bytes = Read(entry, int.MaxValue);
stream.Write(bytes, 0, bytes.Length);
}
else
{
using var input = File.OpenRead(entry.PhysicalPath);
input.CopyTo(stream);
}
});
}
public static void WriteNewFile(string destination, Action<Stream> write)
{
CheckNoLinks(destination);
if (File.Exists(destination))
throw new IOException("Destination already exists: " + destination);
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(destination));
string temporary = destination + "." + Guid.NewGuid().ToString("N") + ".partial";
try
{
using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write))
write(stream);
File.Move(temporary, destination);
}
finally
{
if (File.Exists(temporary))
File.Delete(temporary);
}
}
public static bool Matches(ResourceEntry entry, string query, string category = "All", string source = "All")
{
if (category != "All" && entry.Category != category || source != "All" && entry.Source != source)
return false;
return Matches(entry, SplitQuery(query), category, source);
}
public static string[] SplitQuery(string query) => (query ?? "").Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
public static bool Matches(ResourceEntry entry, string[] terms, string category, string source)
{
if (category != "All" && entry.Category != category || source != "All" && entry.Source != source)
return false;
foreach (string word in terms)
{
bool exclude = word.StartsWith("-", StringComparison.Ordinal);
string term = exclude ? word[1..] : word;
bool match = term.StartsWith("ext:", StringComparison.OrdinalIgnoreCase)
? entry.Extension.Equals("." + term[4..].TrimStart('.'), StringComparison.OrdinalIgnoreCase)
: entry.Path.IndexOf(term.Replace('/', '\\'), StringComparison.OrdinalIgnoreCase) >= 0;
if (match == exclude)
return false;
}
return true;
}
public static string ExportPath(string root, string virtualPath)
{
string[] parts = virtualPath.Replace('\\', '/').Split('/');
if (parts.Any(p => string.IsNullOrWhiteSpace(p) || p is "." or ".." || p.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) >= 0 || p.Contains(':')))
throw new InvalidDataException($"Unsafe resource path: {virtualPath}");
string destination = System.IO.Path.GetFullPath(System.IO.Path.Combine(root, System.IO.Path.Combine(parts)));
string prefix = System.IO.Path.GetFullPath(root).TrimEnd(System.IO.Path.DirectorySeparatorChar) + System.IO.Path.DirectorySeparatorChar;
if (!destination.StartsWith(prefix, StringComparison.Ordinal))
throw new InvalidDataException("Export path escapes its destination.");
CheckNoLinks(destination);
return destination;
}
public static void CheckNoLinks(string fullPath, string message = "Use a path without symbolic links")
{
for (string path = System.IO.Path.GetFullPath(fullPath); path != null; path = System.IO.Path.GetDirectoryName(path))
{
if ((File.Exists(path) || Directory.Exists(path)) && (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0)
throw new IOException($"{message}: {path}");
if (path == System.IO.Path.GetPathRoot(path))
break;
}
}
public void Dispose() => FileSystem.DisposeAllInMemoryArchives();
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 3015cba398a642f8b59df6ba01e3957e
@@ -0,0 +1,182 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Core.DataReader.Gdb;
using Core.DataReader.Sce;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using UnityEditor;
using UnityEngine;
public sealed partial class ResourceBrowserWindow
{
private bool _inspectData, _dialogueOnly, _showVariables;
private int _databaseTable, _scriptPage;
private uint? _pendingScriptBlock;
private uint _listedBlock = uint.MaxValue;
private List<ResourceScriptLine> _scriptLines;
private string _scriptFind = "";
private void ClearDataView()
{
_inspectData = false;
_databaseTable = 0;
_scriptPage = 0;
_scriptLines = null;
_listedBlock = uint.MaxValue;
_pendingScriptBlock = null;
_scriptFind = "";
_showVariables = false;
}
private void DrawScriptView(SceFile file)
{
SceScriptBlock[] blocks = file.ScriptBlocks.Values.OrderBy(b => b.Id).ToArray();
if (_pendingScriptBlock is { } requested)
{
int index = Array.FindIndex(blocks, b => b.Id == requested);
if (index >= 0)
{
_recordIndex = index;
_recordQuery = "";
}
else
_error = $"Script block {requested} is not present in {_selected.Path}.";
_pendingScriptBlock = null;
}
int picked = PickRecord(blocks.Select(b => $"Block {b.Id} · {b.Description}").ToArray());
if (picked < 0)
return;
SceScriptBlock block = blocks[picked];
using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar))
{
_dialogueOnly = GUILayout.Toggle(_dialogueOnly, "Dialogue only", EditorStyles.toolbarButton);
_showVariables = GUILayout.Toggle(_showVariables, $"Locals ({block.UserVariables.Length})", EditorStyles.toolbarButton);
if (GUILayout.Button("Export script…", EditorStyles.toolbarButton))
ExportScript(file);
}
GUILayout.Label("Block-relative byte offsets · mask bits denote variable parameters · inspection listing", EditorStyles.wordWrappedMiniLabel);
if (_showVariables)
{
_objectView.Draw(block.UserVariables, DetailWidth);
return;
}
if (_scriptLines == null || _listedBlock != block.Id)
{
_scriptLines = ResourceScriptListing.Decode(block, file.Codepage);
_listedBlock = block.Id;
_scriptPage = 0;
}
_scriptFind = EditorGUILayout.TextField("Find in block", _scriptFind);
string[] lines = _scriptLines.Where(line => !_dialogueOnly || line.Dialogue != null || line.IsError)
.Select(line => _dialogueOnly && !line.IsError ? $"{line.Offset:X6} {line.Dialogue}" : line.Text)
.Where(line => line.IndexOf(_scriptFind, StringComparison.OrdinalIgnoreCase) >= 0).ToArray();
int pages = Mathf.Max(1, (lines.Length + 99) / 100);
_scriptPage = Mathf.Clamp(EditorGUILayout.IntField($"Page / {pages} · {lines.Length} lines", _scriptPage + 1) - 1, 0, pages - 1);
string text = string.Join("\n", lines.Skip(_scriptPage * 100).Take(100));
if (text.Length > 60000)
text = text[..60000] + "\n[Display limit reached. Export the script for complete text.]";
_detailScroll = EditorGUILayout.BeginScrollView(_detailScroll);
var style = new GUIStyle(EditorStyles.textArea) { wordWrap = true };
float height = Mathf.Max(100, style.CalcHeight(new GUIContent(text), Mathf.Max(100, DetailWidth - 30)));
EditorGUILayout.SelectableLabel(text, style, GUILayout.Height(height), GUILayout.ExpandWidth(true));
EditorGUILayout.EndScrollView();
}
private void ExportScript(SceFile file)
{
string path = EditorUtility.SaveFilePanel("Export inspection listing", "", _selected.Name + (_dialogueOnly ? ".dialogue" : ""), "txt");
if (path.Length == 0)
return;
try
{
_catalog.CheckExportDestination(path);
ResourceCatalog.WriteNewFile(path, stream =>
{
using var writer = new StreamWriter(stream, new UTF8Encoding(false), 4096, leaveOpen: true);
ResourceScriptListing.Export(file, writer, _dialogueOnly);
});
_status = "Exported " + path;
}
catch (Exception ex) { _error = ex.Message; }
}
private void DrawDatabaseView(GdbFile database)
{
int table = GUILayout.Toolbar(_databaseTable, new[] { "Items", "Actors", "Skills", "Combos" });
if (table != _databaseTable)
{
_databaseTable = table;
_recordIndex = 0;
_recordQuery = "";
_objectView.Reset();
}
(string label, object record)[] records = table switch
{
0 => database.GameItemInfos.OrderBy(p => p.Key).Select(p => ($"{p.Key} · {p.Value.Name} · {p.Value.Type}", (object)p.Value)).ToArray(),
1 => database.CombatActorInfos.OrderBy(p => p.Key).Select(p => ($"{p.Key} · {p.Value.Name} · {p.Value.ModelId}", (object)p.Value)).ToArray(),
2 => database.SkillInfos.OrderBy(p => p.Key).Select(p => ($"{p.Key} · {p.Value.Name}", (object)p.Value)).ToArray(),
_ => database.ComboSkillInfos.OrderBy(p => p.Key).Select(p => ($"{p.Key} · {p.Value.Name}", (object)p.Value)).ToArray(),
};
int index = PickRecord(records.Select(r => r.label).ToArray());
if (index >= 0)
_objectView.Draw(records[index].record, DetailWidth);
}
private void ExportJson()
{
string path = EditorUtility.SaveFilePanel("Export decoded resource JSON", "", _selected.Name, "json");
if (path.Length == 0)
return;
try
{
_catalog.CheckExportDestination(path);
WriteJson(_decoded, path);
_status = "Exported " + path;
}
catch (Exception ex) { _error = ex.Message; }
}
public static void WriteJson(object value, string path)
{
ResourceCatalog.WriteNewFile(path, stream =>
{
using var writer = new StreamWriter(stream, new UTF8Encoding(false), 4096, leaveOpen: true);
var serializer = new JsonSerializer { Formatting = Formatting.Indented, ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
serializer.Converters.Add(new StringEnumConverter());
serializer.Serialize(writer, value);
});
}
private void OpenSceneScript(string city, uint block)
{
ResourceEntry script = _catalog.Find(Core.Contract.Constants.FileConstants.GetSceneSceFileVirtualPath(city));
using (new EditorGUI.DisabledScope(script == null))
{
if (GUILayout.Button("Open script block " + block))
{
Select(script);
if (_selected == script)
_pendingScriptBlock = block;
GUIUtility.ExitGUI();
}
}
}
private void OpenEffectEditor()
{
EditorPrefs.SetString(Variant + ".OriginalEffect.DataPath", _catalog.Root);
EditorPrefs.SetInt(Variant + ".OriginalEffect.Codepage", _catalog.Codepage);
EditorApplication.ExecuteMenuItem(Variant + "/Effect Editor");
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 14551be0f098418692a6ae69db532a53
@@ -0,0 +1,56 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser
{
using System;
using System.IO;
using System.Text;
using Core.DataReader.Sce;
public enum ResourceExportMode
{
Original, Script, Dialogue, Json
}
public static class ResourceExport
{
public static bool Supports(ResourceEntry entry, ResourceExportMode mode) => mode switch
{
ResourceExportMode.Original => true,
ResourceExportMode.Script or ResourceExportMode.Dialogue => entry.Extension == ".sce",
_ => entry.Category is "Models" or "Scenes" or "Navigation" or "Lights" or "Scripts" or "Database" or "Effects",
};
public static string Suffix(ResourceExportMode mode) => mode switch
{
ResourceExportMode.Script => ".txt",
ResourceExportMode.Dialogue => ".dialogue.txt",
ResourceExportMode.Json => ".json",
_ => "",
};
public static void Write(ResourceCatalog catalog, ResourceEntry entry, ResourceExportMode mode, string destination)
{
catalog.CheckExportDestination(destination);
if (mode == ResourceExportMode.Original)
{
catalog.ExportOriginal(entry, destination);
return;
}
object data = ResourceFormats.Read(entry, catalog.Read(entry), catalog.Codepage);
if (data == null)
throw new InvalidDataException("No decoder is available for this resource.");
if (mode == ResourceExportMode.Json)
ResourceBrowserWindow.WriteJson(data, destination);
else
ResourceCatalog.WriteNewFile(destination, stream =>
{
using var writer = new StreamWriter(stream, new UTF8Encoding(false), 4096, leaveOpen: true);
ResourceScriptListing.Export((SceFile)data, writer, mode == ResourceExportMode.Dialogue);
});
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e49eeacb8c8b4a6a94e1160cb9331f16
@@ -0,0 +1,68 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser
{
using System;
using Core.DataReader;
using Core.DataReader.Cvd;
using Core.DataReader.Mov;
using Core.DataReader.Scn;
using Core.DataReader.Nav;
using Core.DataReader.Lgt;
using Core.DataReader.Msh;
using Core.DataReader.Mtl;
using Core.DataReader.Mv3;
using Core.DataReader.Pol;
using Core.DataReader.Sce;
using Core.DataReader.Gdb;
using Core.DataReader.Data;
using Core.DataReader.Dat;
using Core.DataReader.Par;
public static class ResourceFormats
{
public static object Read(ResourceEntry entry, byte[] bytes, int codepage) => entry.Extension switch
{
".sce" => Read(new SceFileReader(), bytes, codepage),
".gdb" => Read(new GdbFileReader(), bytes, codepage),
".data" when entry.Name.Equals("flexeff.data", StringComparison.OrdinalIgnoreCase) => Read(new EffectDefinitionFileReader(), bytes, codepage),
".dat" when entry.Name.Equals("efflinker.dat", StringComparison.OrdinalIgnoreCase) => Read(new EffectLinkerFileReader(), bytes, codepage),
".par" when bytes.Length >= 6 && System.Text.Encoding.ASCII.GetString(bytes, 0, 6) == "sgpar\0" => Read(new ParticleFileReader(), bytes, codepage),
".par" or ".spar" when bytes.Length >= 48 && System.Text.Encoding.ASCII.GetString(bytes, 8, 40) == "__PARTICLE_EFFECT(Softstar_Ltd)_EXPORT__" => Read(new SparFileReader(), bytes, codepage),
".csf" => Read(new ParticleShapeFileReader(), bytes, codepage),
".scn" => Read(new ScnFileReader(), bytes, codepage),
".nav" => Read(new NavFileReader(), bytes, codepage),
".lgt" => Read(new LgtFileReader(), bytes, codepage),
".pol" => Read(new PolFileReader(), bytes, codepage),
".cvd" => Read(new CvdFileReader(), bytes, codepage),
".mv3" => Read(new Mv3FileReader(), bytes, codepage),
".msh" => Read(new MshFileReader(), bytes, codepage),
".mov" => Read(new MovFileReader(), bytes, codepage),
".mtl" => Read(new MtlFileReader(), bytes, codepage),
_ => null,
};
public static T Read<T>(IFileReader<T> reader, byte[] bytes, int codepage) => reader.Read(bytes, codepage);
public static readonly string[] Categories = { "All", "Models", "Textures", "Scenes", "Navigation", "Scripts", "Database", "Effects", "Lights", "Text", "Audio", "Video", "Other" };
public static string Category(string extension) => extension.ToLowerInvariant() switch
{
".pol" or ".cvd" or ".mv3" or ".msh" or ".mov" or ".mtl" => "Models",
".dds" or ".tga" or ".bmp" or ".bm" or ".png" or ".jpg" or ".jpeg" => "Textures",
".scn" => "Scenes",
".nav" => "Navigation",
".sce" => "Scripts",
".gdb" => "Database",
".par" or ".spar" or ".csf" or ".data" or ".dat" => "Effects",
".lgt" => "Lights",
".ini" or ".txt" or ".gbf" or ".cfg" or ".csv" or ".xml" or ".json" or ".log" => "Text",
".wav" or ".mp3" or ".ogg" => "Audio",
".webm" or ".mp4" or ".bik" or ".avi" => "Video",
_ => "Other",
};
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 089d14f2ee414b1da0a97231254cb2d8
@@ -0,0 +1,130 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser
{
using System;
using System.IO;
// Validate dimensions before legacy decoders allocate buffers or access unsafe pixel data.
public static class ResourceImageData
{
public static byte[] Prepare(string extension, byte[] data)
{
long width, height;
switch (extension)
{
case ".tga":
Require(data, 18);
if (data[1] != 0 || data[2] != 2 || data[16] is not (24 or 32))
throw new InvalidDataException("Only uncompressed true-color 24/32-bit TGA images are supported.");
width = Little16(data, 12);
height = Little16(data, 14);
CheckSize(width, height);
int stride = data[16] / 8;
int offset = 18 + data[0];
Require(data, checked(offset + (int)(width * height * stride)));
// The runtime decoder expects a bottom-left origin and no image ID.
var normalized = new byte[checked(18 + (int)(width * height * stride))];
Array.Copy(data, normalized, 18);
normalized[0] = 0;
normalized[17] &= 15;
for (int y = 0; y < height; y++)
{
int sourceY = (data[17] & 32) != 0 ? (int)height - y - 1 : y;
for (int x = 0; x < width; x++)
{
int sourceX = (data[17] & 16) != 0 ? (int)width - x - 1 : x;
Array.Copy(data, offset + (sourceY * (int)width + sourceX) * stride,
normalized, 18 + (y * (int)width + x) * stride, stride);
}
}
return normalized;
case ".dds":
Require(data, 128);
if (Little32(data, 0) != 0x20534444)
throw new InvalidDataException("Invalid DDS signature.");
height = Little32(data, 12);
width = Little32(data, 16);
break;
case ".bmp":
case ".bm":
Require(data, 54);
if (data[0] != 'B' || data[1] != 'M' || Little32(data, 14) < 40)
throw new InvalidDataException("Unsupported BMP header.");
width = Math.Abs((long)(int)Little32(data, 18));
height = Math.Abs((long)(int)Little32(data, 22));
break;
case ".png":
Require(data, 24);
if (Big32(data, 0) != 0x89504e47 || Big32(data, 4) != 0x0d0a1a0a || Big32(data, 12) != 0x49484452)
throw new InvalidDataException("Invalid PNG header.");
width = Big32(data, 16);
height = Big32(data, 20);
break;
case ".jpg":
case ".jpeg":
(width, height) = JpegSize(data);
break;
default:
throw new InvalidDataException("Unsupported image format.");
}
CheckSize(width, height);
return data;
}
private static (long, long) JpegSize(byte[] data)
{
Require(data, 4);
if (data[0] != 255 || data[1] != 216)
throw new InvalidDataException("Invalid JPEG signature.");
int offset = 2;
while (offset < data.Length)
{
if (data[offset++] != 255)
throw new InvalidDataException("Invalid JPEG marker.");
while (offset < data.Length && data[offset] == 255)
offset++;
Require(data, offset + 1);
byte marker = data[offset++];
if (marker is 0xda or 0xd9)
break;
if (marker is 0x01 or >= 0xd0 and <= 0xd8)
continue;
Require(data, offset + 2);
int length = data[offset] * 256 + data[offset + 1];
if (length < 2)
throw new InvalidDataException("Invalid JPEG segment length.");
Require(data, offset + length);
if (marker >= 0xc0 && marker <= 0xcf && marker is not (0xc4 or 0xc8 or 0xcc))
{
if (length < 8)
throw new InvalidDataException("Invalid JPEG frame header.");
return (data[offset + 5] * 256 + data[offset + 6], data[offset + 3] * 256 + data[offset + 4]);
}
offset += length;
}
throw new InvalidDataException("JPEG dimensions were not found.");
}
private static void CheckSize(long width, long height)
{
if (width <= 0 || height <= 0 || width > 16384 || height > 16384 || width * height > 32 * 1024 * 1024)
throw new InvalidDataException("Image dimensions are invalid or exceed the preview limit (16384 per side, 32 megapixels).");
}
private static void Require(byte[] data, int length)
{
if (data.Length < length)
throw new InvalidDataException("Truncated image data.");
}
private static int Little16(byte[] data, int at) => data[at] | data[at + 1] << 8;
private static uint Little32(byte[] data, int at) => (uint)(data[at] | data[at + 1] << 8 | data[at + 2] << 16 | data[at + 3] << 24);
private static uint Big32(byte[] data, int at) => (uint)(data[at] << 24 | data[at + 1] << 16 | data[at + 2] << 8 | data[at + 3]);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9a7bb6218f094ab48c81b90f1862fee9
@@ -0,0 +1,385 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.Video;
// Owns a single selection. Pending extraction can finish after disposal but cannot create Unity objects.
public sealed class ResourceMediaPreview : IDisposable
{
private readonly ResourceEntry _entry;
private readonly string _temporaryDirectory;
private Task<string> _file;
private UnityWebRequest _request;
private UnityEditor.Editor _audioEditor;
private GameObject _root;
private Scene _scene;
private double _started;
private bool _disposed, _seeking, _pauseAfterSeek;
private bool _wasUpdating = true;
private double _seekTime, _seekStarted;
private double? _queuedSeek;
public AudioClip Audio
{
get; private set;
}
public VideoPlayer Video
{
get; private set;
}
public string Error
{
get; private set;
}
public bool Ready => Audio != null || Video != null && Video.isPrepared;
public bool Loading => Error == null && !Ready;
public string TemporaryDirectory => _temporaryDirectory;
private static string TemporaryRoot => Path.GetFullPath(Path.Combine(Application.dataPath, "../../workspace/ResourceBrowserMedia"));
public ResourceMediaPreview(ResourceCatalog catalog, ResourceEntry entry)
{
_entry = entry;
_started = EditorApplication.timeSinceStartup;
if (entry.Extension == ".bik")
{
Error = "BIK is not decoded by Unity. Export the original, or select a converted WebM file.";
return;
}
var sizes = catalog.GetSizes(entry);
if ((entry.IsArchived || entry.Category == "Audio") && sizes.length + sizes.packedLength > ResourceCatalog.PreviewByteLimit)
throw new InvalidDataException("Media exceeds the 64 MiB extraction/audio preview limit. Export the original instead.");
if (entry.IsArchived)
{
using var process = Process.GetCurrentProcess();
_temporaryDirectory = Path.Combine(TemporaryRoot, process.Id + "-" + Guid.NewGuid().ToString("N"));
string destination = Path.Combine(_temporaryDirectory, "preview" + entry.Extension);
_file = Task.Run(() =>
{
catalog.ExportOriginal(entry, destination);
return destination;
});
}
else
_file = Task.FromResult(entry.PhysicalPath);
}
// AudioClip's native inspector repaints itself during playback. Refresh loading/video
// state here, including one final repaint when loading or playback stops.
public bool Tick()
{
if (_disposed)
return false;
bool repaint = _wasUpdating;
UpdateMedia();
_wasUpdating = Error == null && (Loading || Video != null && (Video.isPlaying || _seeking || _queuedSeek.HasValue));
return repaint || _wasUpdating;
}
private void UpdateMedia()
{
if (_disposed || Error != null)
return;
try
{
if (_file is { IsCompleted: true })
{
string path = _file.GetAwaiter().GetResult();
_file = null;
if (_entry.Category == "Audio")
{
AudioType type = _entry.Extension switch
{
".wav" => AudioType.WAV,
".mp3" => AudioType.MPEG,
_ => AudioType.OGGVORBIS
};
_request = UnityWebRequestMultimedia.GetAudioClip(new Uri(path).AbsoluteUri, type);
((DownloadHandlerAudioClip)_request.downloadHandler).streamAudio = true;
_request.SendWebRequest();
}
else
{
_scene = EditorSceneManager.NewPreviewScene();
_root = new GameObject("Resource video preview") { hideFlags = HideFlags.HideAndDontSave };
SceneManager.MoveGameObjectToScene(_root, _scene);
Video = _root.AddComponent<VideoPlayer>();
Video.playOnAwake = false;
Video.renderMode = VideoRenderMode.APIOnly;
Video.audioOutputMode = VideoAudioOutputMode.Direct;
Video.source = VideoSource.Url;
Video.url = new Uri(path).AbsoluteUri;
Video.errorReceived += OnVideoError;
Video.seekCompleted += OnVideoSeek;
Video.sendFrameReadyEvents = true;
Video.frameReady += OnVideoFrame;
Video.Prepare();
}
}
if (_request is { isDone: true })
{
if (_request.result != UnityWebRequest.Result.Success)
throw new InvalidDataException(_request.error);
Audio = DownloadHandlerAudioClip.GetContent(_request);
if (Audio == null)
throw new InvalidDataException("Unity returned no audio clip.");
Audio.name = _entry.Name;
Audio.hideFlags = HideFlags.HideAndDontSave;
_audioEditor = UnityEditor.Editor.CreateEditor(Audio);
_request.Dispose();
_request = null;
}
if (Loading && EditorApplication.timeSinceStartup - _started > 30)
throw new TimeoutException("Unity did not prepare this media within 30 seconds. Export it to inspect with another player.");
if (!_seeking && _queuedSeek is { } requested)
SeekVideo(requested);
if (_seeking && EditorApplication.timeSinceStartup - _seekStarted > 10)
throw new TimeoutException("Video seek did not produce a frame within 10 seconds.");
if (Video != null && (!Video.isPrepared || Video.isPlaying || _seeking))
EditorApplication.QueuePlayerLoopUpdate();
}
catch (Exception ex)
{
Error = ex.Message;
StopLoading();
}
}
public void SeekVideo(double seconds)
{
if (_disposed || Error != null || !double.IsFinite(seconds) || Video == null || !Video.isPrepared || !Video.canSetTime)
return;
_wasUpdating = true;
if (_seeking)
{
_queuedSeek = seconds;
return;
}
_queuedSeek = null;
_seeking = true;
_pauseAfterSeek = !Video.isPlaying;
_seekStarted = EditorApplication.timeSinceStartup;
// Container duration can include timestamps past the last decodable frame.
// Leave a small end margin so Play does not interpret a paused seek as EOF and restart.
double endMargin = Math.Max(0.1, 2 / Math.Max(0.001, Video.frameRate));
_seekTime = Math.Clamp(seconds, 0, Math.Max(0, Video.length - endMargin));
if (_pauseAfterSeek)
SetSeekMute(true);
Video.time = _seekTime;
EditorApplication.QueuePlayerLoopUpdate();
}
private void SetSeekMute(bool mute)
{
for (ushort track = 0; track < Math.Min(Video.audioTrackCount, Video.controlledAudioTrackCount); track++)
Video.SetDirectAudioMute(track, mute);
}
private void OnVideoSeek(VideoPlayer source)
{
if (_disposed || Error != null || !_seeking || source != Video)
return;
// Some URL decoders do not present a new frame while paused. Decode one silently.
if (_pauseAfterSeek)
source.Play();
EditorApplication.QueuePlayerLoopUpdate();
}
private void OnVideoFrame(VideoPlayer source, long frame)
{
if (_disposed || Error != null || !_seeking || source != Video ||
Math.Abs(frame / Math.Max(0.001, source.frameRate) - _seekTime) > Math.Max(0.2, 1 / Math.Max(0.001, source.frameRate)))
return;
if (_pauseAfterSeek)
{
source.Pause();
SetSeekMute(false);
}
_seeking = false;
_pauseAfterSeek = false;
_wasUpdating = true;
}
private void OnVideoError(VideoPlayer source, string message)
{
_wasUpdating = true;
Error = message;
StopLoading();
}
public void Draw()
{
if (Error != null)
{
EditorGUILayout.HelpBox(Error, MessageType.Warning);
return;
}
if (!Ready)
{
EditorGUILayout.HelpBox("Preparing media…", MessageType.Info);
return;
}
if (Audio != null)
{
GUILayout.Label($"{Audio.length:F2} s · {Audio.frequency:N0} Hz · {Audio.channels} channels");
using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar))
_audioEditor.OnPreviewSettings();
EditorGUILayout.HelpBox("Unity audio preview: Play / Auto Play / Loop. Click the preview to seek. Waveforms require imported assets and are not generated here.", MessageType.None);
Rect audioRect = GUILayoutUtility.GetRect(100, 10000, 100, 250);
GUI.BeginGroup(audioRect);
try
{
_audioEditor.DrawPreview(new Rect(0, 0, audioRect.width, audioRect.height));
}
finally
{
GUI.EndGroup();
}
return;
}
using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar))
{
using (new EditorGUI.DisabledScope(_seeking || _queuedSeek.HasValue))
{
if (GUILayout.Button(Video.isPlaying ? "Pause" : "Play", EditorStyles.toolbarButton, GUILayout.Width(60)))
{
if (Video.isPlaying)
Video.Pause();
else
Video.Play();
}
}
Video.isLooping = GUILayout.Toggle(Video.isLooping, "Loop", EditorStyles.toolbarButton, GUILayout.Width(50));
using (new EditorGUI.DisabledScope(!Video.canSetTime))
{
float displayedTime = (float)(_queuedSeek ?? (_seeking ? _seekTime : Video.time));
EditorGUI.BeginChangeCheck();
float sliderTime = GUILayout.HorizontalSlider(displayedTime, 0, (float)Video.length);
if (EditorGUI.EndChangeCheck())
SeekVideo(sliderTime);
EditorGUI.BeginChangeCheck();
float enteredTime = EditorGUILayout.DelayedFloatField(displayedTime, GUILayout.Width(70));
if (EditorGUI.EndChangeCheck())
SeekVideo(enteredTime);
}
}
GUILayout.Label($"{Video.width} × {Video.height} · {Video.frameRate:F2} fps · {Video.time:F2} / {Video.length:F2} s", EditorStyles.miniLabel);
Rect rect = GUILayoutUtility.GetRect(100, 10000, 100, 10000, GUILayout.ExpandHeight(true));
EditorGUI.DrawRect(rect, Color.black);
if (Video.texture != null)
GUI.DrawTexture(rect, Video.texture, ScaleMode.ScaleToFit);
}
private void StopLoading()
{
_seeking = false;
_pauseAfterSeek = false;
_queuedSeek = null;
_request?.Abort();
_request?.Dispose();
_request = null;
if (Video != null)
Video.Stop();
}
private static void RemoveTemporaryFiles(string directory)
{
if (directory == null)
return;
try
{
if (Directory.Exists(directory))
Directory.Delete(directory, true);
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
public static void CleanupStaleTemporaryFiles()
{
try
{
if (!Directory.Exists(TemporaryRoot))
return;
ResourceCatalog.CheckNoLinks(TemporaryRoot);
foreach (string directory in Directory.EnumerateDirectories(TemporaryRoot))
{
string name = Path.GetFileName(directory);
int separator = name.IndexOf('-');
if (separator <= 0 || !int.TryParse(name[..separator], out int processId) || processId <= 0 ||
!Guid.TryParseExact(name[(separator + 1)..], "N", out _) ||
(File.GetAttributes(directory) & FileAttributes.ReparsePoint) != 0)
continue;
try
{
using var process = Process.GetProcessById(processId);
if (!process.HasExited)
continue;
}
catch (ArgumentException) { } // No process owns this directory anymore.
catch (InvalidOperationException) { continue; }
catch (Win32Exception) { continue; }
catch (NotSupportedException) { continue; }
RemoveTemporaryFiles(directory);
}
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
public void Dispose()
{
if (_disposed)
return;
_disposed = true;
StopLoading();
if (_audioEditor != null)
UnityEngine.Object.DestroyImmediate(_audioEditor);
if (Audio != null)
UnityEngine.Object.DestroyImmediate(Audio);
if (Video != null)
{
Video.errorReceived -= OnVideoError;
Video.seekCompleted -= OnVideoSeek;
Video.frameReady -= OnVideoFrame;
}
if (_root != null)
UnityEngine.Object.DestroyImmediate(_root);
if (_scene.IsValid())
EditorSceneManager.ClosePreviewScene(_scene);
Audio = null;
Video = null;
_audioEditor = null;
if (_file != null)
{
string directory = _temporaryDirectory;
_ = _file.ContinueWith(task =>
{
_ = task.Exception;
RemoveTemporaryFiles(directory);
}, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
_file = null;
}
else
RemoveTemporaryFiles(_temporaryDirectory);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 410fdcfdcb51414c9de836e3d06bbcfd
@@ -0,0 +1,353 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Core.DataReader.Cvd;
using Core.DataReader.Mov;
using Core.DataReader.Msh;
using Core.DataReader.Mtl;
using Core.DataReader.Mv3;
using Core.DataReader.Pol;
using Engine.Core.Abstraction;
using Engine.Core.Implementation;
using Engine.Extensions;
using Game.Data;
using Game.Rendering.Material;
using Game.Rendering.Renderer;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;
public sealed class ResourceModelPreview : IDisposable
{
private readonly ResourceCatalog _catalog;
private readonly Scene _scene;
private readonly Camera _camera;
private readonly GameMaterialManager _materials;
private readonly Dictionary<string, (ITexture2D texture, bool alpha)> _textures = new(StringComparer.OrdinalIgnoreCase);
private readonly List<IDisposable> _renderers = new();
private readonly List<Action<float>> _samplers = new();
private RenderTexture _target;
private Vector2 _orbit = new(145, 20);
private Vector3 _center;
private float _distance = 5;
private Bounds? _fallbackBounds;
public GameObject Root
{
get;
}
public float Duration
{
get; private set;
}
public string Statistics
{
get; private set;
}
public Dictionary<string, bool> Dependencies { get; } = new(StringComparer.OrdinalIgnoreCase);
public ResourceModelPreview(ResourceCatalog catalog, bool toon)
{
_catalog = catalog;
_scene = EditorSceneManager.NewPreviewScene();
Root = NewObject("Resource preview");
var cameraObject = NewObject("Preview camera");
_camera = cameraObject.AddComponent<Camera>();
_camera.enabled = false;
_camera.scene = _scene;
_camera.clearFlags = CameraClearFlags.SolidColor;
_camera.backgroundColor = new Color(0.12f, 0.13f, 0.15f);
_camera.fieldOfView = 40;
_camera.nearClipPlane = 0.01f;
_camera.farClipPlane = 10000;
var light = NewObject("Preview light").AddComponent<Light>();
light.type = LightType.Directional;
light.intensity = 1.2f;
light.transform.rotation = Quaternion.Euler(45, -35, 0);
_materials = new GameMaterialManager(new UnityMaterialFactory(), toon);
}
private GameObject NewObject(string name, Transform parent = null)
{
var go = new GameObject(name) { hideFlags = HideFlags.HideAndDontSave };
SceneManager.MoveGameObjectToScene(go, _scene);
if (parent != null)
go.transform.SetParent(parent, false);
return go;
}
public void Load(ResourceEntry entry, object decoded)
{
GameObject go = NewObject(entry.Name, Root.transform);
var textures = new ModelTextures(this, DirectoryOf(entry.Path));
switch (decoded)
{
case PolFile pol:
var poly = go.AddComponent<PolyModelRenderer>();
_renderers.Add(poly);
poly.Render(pol, textures, _materials, isStaticObject: true,
textureFactory: new UnityTextureFactory(), animateWater: false);
break;
case CvdFile cvd:
var cvdRenderer = go.AddComponent<CvdModelRenderer>();
_renderers.Add(cvdRenderer);
cvdRenderer.Init(cvd, textures, _materials);
Duration = Mathf.Max(Duration, cvd.AnimationDuration);
_samplers.Add(t => cvdRenderer.SetCurrentTime(Mathf.Clamp(t, 0, cvd.AnimationDuration)));
break;
case Mv3File mv3:
var mv3Renderer = go.AddComponent<Mv3ModelRenderer>();
_renderers.Add(mv3Renderer);
mv3Renderer.Init(mv3, _materials, textures);
Duration = Mathf.Max(Duration, (float)mv3.TotalGameBoxTicks / UnityPrimitivesConvertor.GameBoxTicksPerSecond);
_samplers.Add(mv3Renderer.SampleAnimation);
break;
case MshFile:
case MovFile:
string directory = DirectoryOf(entry.Path);
string folder = FileName(directory);
string mshPath = decoded is MshFile ? entry.Path : Path.ChangeExtension(entry.Path, ".msh");
if (_catalog.Find(mshPath) == null)
mshPath = CombinePath(directory, folder + ".msh");
string mtlPath = Path.ChangeExtension(mshPath, ".mtl");
if (_catalog.Find(mtlPath) == null)
mtlPath = CombinePath(directory, folder + ".mtl");
var msh = decoded as MshFile ?? (MshFile)ReadDependency(mshPath);
var mtl = (MtlFile)ReadDependency(mtlPath);
var skeletal = go.AddComponent<SkeletalModelRenderer>();
_renderers.Add(skeletal);
skeletal.Init(msh, mtl, _materials, new ModelTextures(this, DirectoryOf(mtlPath)));
if (decoded is MovFile mov)
{
Duration = mov.Duration;
_samplers.Add(t => skeletal.SampleAnimation(mov, t));
}
break;
default:
throw new NotSupportedException("No model preview for " + entry.Extension);
}
foreach (Transform child in Root.GetComponentsInChildren<Transform>(true))
child.gameObject.hideFlags = HideFlags.HideAndDontSave;
Sample(0);
Frame();
MeshFilter[] meshes = Root.GetComponentsInChildren<MeshFilter>();
Statistics = $"{meshes.Length} meshes · {meshes.Sum(m => m.sharedMesh != null ? m.sharedMesh.vertexCount : 0):N0} vertices · " +
$"{Root.GetComponentsInChildren<Renderer>().SelectMany(r => r.sharedMaterials).Distinct().Count()} materials";
}
private object ReadDependency(string path)
{
ResourceEntry entry = _catalog.Find(path);
Dependencies[path] = entry != null;
if (entry == null)
throw new FileNotFoundException("Missing model dependency: " + path);
return ResourceFormats.Read(entry, _catalog.Read(entry), _catalog.Codepage);
}
public static string DirectoryOf(string path)
{
path = path.Replace('/', '\\');
int slash = path.LastIndexOf('\\');
return slash < 0 ? "" : path[..slash];
}
public static string FileName(string path) => path.Replace('/', '\\').Split('\\')[^1];
public static string CombinePath(string directory, string name) => string.IsNullOrEmpty(directory) ? name : directory + "\\" + name;
private sealed class ModelTextures : ITextureResourceProvider
{
private readonly ResourceModelPreview _owner;
private readonly string _directory;
public ModelTextures(ResourceModelPreview owner, string directory)
{
_owner = owner;
_directory = directory;
}
public string GetTexturePath(string name) => CombinePath(_directory, name);
public ITexture2D GetTexture(string name) => GetTexture(name, out _);
public ITexture2D GetTexture(string name, out bool hasAlphaChannel)
{
if (string.IsNullOrEmpty(name))
{
hasAlphaChannel = false;
return new UnityTexture2D(Texture2D.whiteTexture);
}
string original = GetTexturePath(name);
string dds = Path.ChangeExtension(original, ".dds");
ResourceEntry entry = _owner._catalog.Find(dds) ?? _owner._catalog.Find(original);
string path = entry?.Path ?? original;
_owner.Dependencies[path] = entry != null;
if (entry == null)
{
hasAlphaChannel = false;
return new UnityTexture2D(Texture2D.whiteTexture);
}
if (!_owner._textures.TryGetValue(path, out var cached))
{
byte[] bytes = ResourceImageData.Prepare(entry.Extension, _owner._catalog.Read(entry));
ITexture2D texture;
bool alpha;
if (entry.Extension is ".png" or ".jpg" or ".jpeg")
{
var native = new Texture2D(2, 2, TextureFormat.RGBA32, false);
if (!native.LoadImage(bytes))
{
Object.DestroyImmediate(native);
throw new InvalidDataException("Invalid image: " + path);
}
texture = new UnityTexture2D(native);
alpha = entry.Extension == ".png";
}
else
{
using ITextureDataSource source = new TextureLoaderFactory().GetTextureLoader(entry.Extension).Load(bytes, out alpha);
texture = new UnityTextureFactory().CreateTexture(source, TextureCreateOptions.Readable);
}
var nativeTexture = (Texture2D)texture.NativeObject;
nativeTexture.name = path;
nativeTexture.hideFlags = HideFlags.HideAndDontSave;
nativeTexture.wrapMode = TextureWrapMode.Repeat;
_owner._textures[path] = cached = (texture, alpha);
}
hasAlphaChannel = cached.alpha;
return cached.texture;
}
}
public void Sample(float time)
{
foreach (Action<float> sample in _samplers)
sample(time);
}
public void Frame()
{
Renderer[] renderers = Root.GetComponentsInChildren<Renderer>();
Bounds bounds = renderers.Length > 0 ? renderers[0].bounds : (_fallbackBounds ?? new Bounds(Vector3.zero, Vector3.one));
foreach (Renderer renderer in renderers)
bounds.Encapsulate(renderer.bounds);
_center = bounds.center;
_distance = Mathf.Max(0.5f, bounds.extents.magnitude / Mathf.Sin(_camera.fieldOfView * Mathf.Deg2Rad / 2) * 1.2f);
}
public void FramePoints(IEnumerable<Vector3> points)
{
Vector3[] positions = points.ToArray();
var bounds = new Bounds(positions.Length > 0 ? positions[0] : Vector3.zero, Vector3.one);
foreach (Vector3 point in positions)
bounds.Encapsulate(point);
_fallbackBounds = bounds;
Frame();
}
public bool Project(Vector3 world, Rect view, out Vector2 screen)
{
Vector3 point = _camera.WorldToViewportPoint(world);
screen = new Vector2(view.x + point.x * view.width, view.y + (1 - point.y) * view.height);
return point.z > 0;
}
public void Draw(Rect rect)
{
Event e = Event.current;
if (rect.Contains(e.mousePosition))
{
if (e.type == EventType.MouseDrag)
{
if (e.button == 2 || e.shift)
_center += (_camera.transform.right * -e.delta.x + _camera.transform.up * e.delta.y) * (_distance / 600);
else if (e.button == 0)
_orbit += e.delta * new Vector2(0.5f, -0.5f);
e.Use();
}
if (e.type == EventType.ScrollWheel)
{
_distance = Mathf.Clamp(_distance * Mathf.Exp(e.delta.y * 0.06f), 0.05f, 5000);
e.Use();
}
if (e.type == EventType.KeyDown && e.keyCode == KeyCode.F)
{
Frame();
e.Use();
}
}
if (e.type != EventType.Repaint || rect.width < 2 || rect.height < 2)
return;
GUI.DrawTexture(rect, Render(Mathf.CeilToInt(rect.width), Mathf.CeilToInt(rect.height)), ScaleMode.StretchToFill, false);
}
public RenderTexture Render(int width, int height)
{
EnsureTarget(width, height);
_camera.transform.position = _center + Quaternion.Euler(_orbit.y, _orbit.x, 0) * new Vector3(0, 0, -_distance);
_camera.transform.LookAt(_center);
_camera.aspect = (float)width / height;
RenderPipeline.SubmitRenderRequest(_camera, new UniversalRenderPipeline.SingleCameraRequest { destination = _target });
return _target;
}
private void EnsureTarget(int width, int height)
{
if (_target != null && _target.width == width && _target.height == height)
return;
if (_target != null)
{
_target.Release();
Object.DestroyImmediate(_target);
}
_target = new RenderTexture(width, height, 24) { hideFlags = HideFlags.HideAndDontSave };
_target.Create();
}
public void Dispose()
{
// Capture partially initialized resources too: runtime renderers may not yet be IsInitialized.
Mesh[] meshes = Root != null ? Root.GetComponentsInChildren<MeshFilter>().Select(m => m.sharedMesh).Where(m => m != null).Distinct().ToArray() : Array.Empty<Mesh>();
Material[] materials = Root != null ? Root.GetComponentsInChildren<Renderer>().SelectMany(r => r.sharedMaterials).Where(m => m != null).Distinct().ToArray() : Array.Empty<Material>();
foreach (IDisposable renderer in _renderers)
renderer.Dispose();
_renderers.Clear();
_samplers.Clear();
if (Root != null)
Object.DestroyImmediate(Root);
_materials.Dispose();
foreach (Mesh mesh in meshes)
if (mesh != null)
Object.DestroyImmediate(mesh);
foreach (Material material in materials)
if (material != null)
Object.DestroyImmediate(material);
foreach (var texture in _textures.Values)
Object.DestroyImmediate((Texture2D)texture.texture.NativeObject);
_textures.Clear();
if (_target != null)
{
_target.Release();
Object.DestroyImmediate(_target);
_target = null;
}
if (_scene.IsValid())
EditorSceneManager.ClosePreviewScene(_scene);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7c6e08e2b49e4b76b162184e6933dde1
@@ -0,0 +1,198 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser
{
using System;
using System.Linq;
using Core.DataReader.Mtl;
using UnityEditor;
using UnityEngine;
public sealed partial class ResourceBrowserWindow
{
private ResourceModelPreview _model;
private object _decoded;
[SerializeField] private bool _toon, _loop = true;
private bool _playing, _showDependencies;
private float _time, _speed = 1;
private double _lastTick;
private string[] _animationPaths = Array.Empty<string>();
private string[] _animationLabels = Array.Empty<string>();
private void LoadModelView(ResourceEntry entry)
{
_decoded = ResourceFormats.Read(entry, _bytes, _catalog.Codepage);
if (_decoded is MtlFile)
return;
_model = new ResourceModelPreview(_catalog, _toon);
try
{
_model.Load(entry, _decoded);
}
catch
{
_model.Dispose();
_model = null;
throw;
}
string directory = ResourceModelPreview.DirectoryOf(entry.Path);
if (entry.Extension is ".msh" or ".mov")
{
_animationPaths = _catalog.Entries.Where(e => e.Extension == ".mov" &&
ResourceModelPreview.DirectoryOf(e.Path).Equals(directory, StringComparison.OrdinalIgnoreCase)).Select(e => e.Path).ToArray();
_animationLabels = new[] { "Select animation…" }.Concat(_animationPaths.Select(ResourceModelPreview.FileName)).ToArray();
}
_lastTick = EditorApplication.timeSinceStartup;
}
private void TickModel()
{
double now = EditorApplication.timeSinceStartup;
float delta = (float)Math.Min(0.1, now - _lastTick);
_lastTick = now;
if (_model == null || !_playing || EditorApplication.isPlayingOrWillChangePlaymode)
return;
_time += delta * _speed;
if (_time >= _model.Duration)
{
if (_loop && _model.Duration > 0)
_time %= _model.Duration;
else
{
_time = _model.Duration;
_playing = false;
}
}
try
{
_model.Sample(_time);
}
catch (Exception ex)
{
_playing = false;
_error = ex.Message;
}
Repaint();
}
private void ClearModelView()
{
_model?.Dispose();
_model = null;
_decoded = null;
_playing = false;
_time = 0;
_animationPaths = Array.Empty<string>();
_animationLabels = Array.Empty<string>();
}
private void ToggleModelPlayback()
{
_playing = !_playing;
if (_playing && _time >= _model.Duration)
_time = 0;
}
private void DrawModelView()
{
if (_decoded is MtlFile materialFile)
{
_detailScroll = EditorGUILayout.BeginScrollView(_detailScroll);
foreach (var material in materialFile.Materials)
{
EditorGUILayout.LabelField("Material textures", EditorStyles.boldLabel);
foreach (string name in material.TextureFileNames)
{
string path = ResourceModelPreview.CombinePath(ResourceModelPreview.DirectoryOf(_selected.Path), name);
ResourceEntry texture = _catalog.Find(System.IO.Path.ChangeExtension(path, ".dds")) ?? _catalog.Find(path);
using (new EditorGUI.DisabledScope(texture == null))
{
if (GUILayout.Button(name))
{
Select(texture);
GUIUtility.ExitGUI();
}
}
}
string text = Newtonsoft.Json.JsonConvert.SerializeObject(material, Newtonsoft.Json.Formatting.Indented);
var style = new GUIStyle(EditorStyles.textArea) { wordWrap = true };
EditorGUILayout.SelectableLabel(text, style, GUILayout.Height(style.CalcHeight(new GUIContent(text), Mathf.Max(100, DetailWidth - 30))));
}
EditorGUILayout.EndScrollView();
return;
}
if (_model == null)
{
DrawHex();
return;
}
using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar))
{
bool toon = GUILayout.Toggle(_toon, "Toon", EditorStyles.toolbarButton, GUILayout.Width(55));
if (toon != _toon)
{
_toon = toon;
Select(_selected);
GUIUtility.ExitGUI();
}
if (GUILayout.Button("Frame", EditorStyles.toolbarButton, GUILayout.Width(55)))
_model.Frame();
_showDependencies = GUILayout.Toggle(_showDependencies, "Dependencies", EditorStyles.toolbarButton);
}
if (_animationPaths.Length > 0)
{
int current = Array.FindIndex(_animationPaths, p => p.Equals(_selected.Path, StringComparison.OrdinalIgnoreCase)) + 1;
int selected = EditorGUILayout.Popup("Animation", current, _animationLabels);
if (selected != current && selected > 0)
{
Select(_catalog.Find(_animationPaths[selected - 1]));
GUIUtility.ExitGUI();
}
}
if (_model.Duration > 0)
{
using (new EditorGUILayout.HorizontalScope())
{
if (GUILayout.Button(_playing ? "Pause" : "Play", GUILayout.Width(55)))
ToggleModelPlayback();
_loop = GUILayout.Toggle(_loop, "Loop", GUILayout.Width(55));
_speed = EditorGUILayout.Slider("Speed", _speed, 0.1f, 3);
}
EditorGUI.BeginChangeCheck();
_time = EditorGUILayout.Slider("Time (seconds)", _time, 0, _model.Duration);
if (EditorGUI.EndChangeCheck())
{
_playing = false;
try
{
_model.Sample(_time);
}
catch (Exception ex) { _error = ex.Message; }
}
}
GUILayout.Label(_model.Statistics, EditorStyles.miniLabel);
GUILayout.Label("Drag: orbit · Shift / middle drag: pan · Wheel: zoom · F: frame", EditorStyles.miniLabel);
if (_model.Dependencies.Any(pair => !pair.Value))
EditorGUILayout.HelpBox("Some textures are missing (shown white). See Dependencies for exact paths.", MessageType.Warning);
if (_showDependencies)
{
_detailScroll = EditorGUILayout.BeginScrollView(_detailScroll, GUILayout.MaxHeight(150));
foreach (var dependency in _model.Dependencies)
{
if (GUILayout.Button((dependency.Value ? "Open " : "Missing ") + dependency.Key, EditorStyles.linkLabel) && dependency.Value)
{
Select(_catalog.Find(dependency.Key));
GUIUtility.ExitGUI();
}
}
EditorGUILayout.EndScrollView();
}
_model.Draw(GUILayoutUtility.GetRect(100, 10000, 100, 10000, GUILayout.ExpandHeight(true)));
if (Event.current.type is EventType.MouseDrag or EventType.ScrollWheel or EventType.Used)
Repaint();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e1d5aa4c3b834dec933dc4f6e728b26a
@@ -0,0 +1,120 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
// A bounded, lazy field inspector for protocol records, not a serializer or editing framework.
public sealed class ResourceObjectView
{
private readonly HashSet<string> _expanded = new() { "root" };
private readonly Dictionary<string, int> _pages = new();
private Vector2 _scroll;
private float _width;
public void Reset()
{
_expanded.Clear();
_expanded.Add("root");
_pages.Clear();
_scroll = Vector2.zero;
}
public void Draw(object value, float width)
{
_width = width;
_scroll = EditorGUILayout.BeginScrollView(_scroll);
DrawValue("Record", value, "root", 0);
EditorGUILayout.EndScrollView();
}
private void DrawValue(string label, object value, string path, int depth)
{
if (value == null || value is string || value.GetType().IsPrimitive || value.GetType().IsEnum || value is decimal)
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Label(label, GUILayout.Width(180));
string text = value?.ToString() ?? "null";
float height = Mathf.Max(18, EditorStyles.wordWrappedLabel.CalcHeight(new GUIContent(text), Mathf.Max(60, _width - 220)));
EditorGUILayout.SelectableLabel(text, EditorStyles.wordWrappedLabel, GUILayout.Height(height));
}
return;
}
if (depth > 12)
{
GUILayout.Label(label + " (maximum display depth)");
return;
}
int count = value is ICollection collection ? collection.Count : -1;
bool expanded = _expanded.Contains(path);
bool next = EditorGUILayout.Foldout(expanded, count >= 0 ? $"{label} [{count}]" : label + " · " + value.GetType().Name, true);
if (next)
_expanded.Add(path);
else
_expanded.Remove(path);
if (!next)
return;
EditorGUI.indentLevel++;
try
{
if (value is IEnumerable sequence)
{
int page = _pages.TryGetValue(path, out int selected) ? selected : 0;
if (count > 50)
{
page = Mathf.Clamp(EditorGUILayout.IntField("Page (50 per page)", page + 1) - 1, 0, (count - 1) / 50);
_pages[path] = page;
}
int index = 0;
if (value is IDictionary dictionary)
{
foreach (DictionaryEntry entry in dictionary)
{
if (index >= page * 50 + 50)
break;
if (index++ >= page * 50)
DrawValue(entry.Key.ToString(), entry.Value, path + "." + entry.Key, depth + 1);
}
}
else
{
foreach (object item in sequence)
{
if (index >= page * 50 + 50)
break;
if (index++ >= page * 50)
DrawValue((index - 1).ToString(), item, path + "." + (index - 1), depth + 1);
}
}
}
else
{
const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public;
foreach (FieldInfo field in value.GetType().GetFields(flags))
DrawValue(field.Name, field.GetValue(value), path + "." + field.Name, depth + 1);
foreach (PropertyInfo property in value.GetType().GetProperties(flags).Where(p => p.CanRead && p.GetIndexParameters().Length == 0))
{
object child;
try
{
child = property.GetValue(value);
}
catch (Exception ex) { child = ex.GetBaseException().Message; }
DrawValue(property.Name, child, path + "." + property.Name, depth + 1);
}
}
}
finally { EditorGUI.indentLevel--; }
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f0a42008e6a04541bbefb9d7053de469
@@ -0,0 +1,55 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser
{
using System;
using Core.Contract.Constants;
using Core.Contract.Enums;
using Core.DataReader.Nav;
using Core.DataReader.Scn;
using Core.Primitives;
using Engine.Extensions;
using Game.Scene;
using UnityEngine;
using Color32 = UnityEngine.Color32;
public static class ResourceSceneData
{
public static string BackgroundPath(ScnSceneInfo scene) =>
$"{scene.CityName}.cpk\\{scene.Model}\\{(scene.LightMap == 1 ? "1\\" : "")}{scene.Model}.pol";
public static string ObjectPath(ScnSceneInfo scene, ScnObjectInfo item)
{
if (string.IsNullOrEmpty(item.Name) || item.Name.StartsWith('+'))
return null;
if (item.Name.StartsWith('_'))
return FileConstants.GetGameObjectModelFileVirtualPath(scene, item.Name);
return item.Name.Contains('.') ? FileConstants.GetGameObjectModelFileVirtualPath(item.Name) : FileConstants.GetGameItemModelFileVirtualPath(item.Name);
}
public static Vector3 NpcPosition(ScnNpcInfo npc, NavFile nav)
{
Vector3 position = new GameBoxVector3(npc.GameBoxXPosition, npc.GameBoxYPosition, npc.GameBoxZPosition).ToUnityPosition();
if (nav != null && npc.InitBehaviour != ActorBehaviourType.Hold && npc.LayerIndex >= 0 && npc.LayerIndex < nav.Layers.Length)
{
var map = new Tilemap(nav);
if (map.TryGetTile(position, npc.LayerIndex, out NavTile tile))
position.y = tile.GameBoxYPosition.ToUnityYPosition();
}
return position;
}
public static Color32 TileColor(NavTile tile) => tile.IsObstacle ? new Color32(150, 48, 48, 255) :
tile.IsWalkable() ? new Color32(72, 150, 100, 255) : new Color32(196, 145, 47, 255);
public static Vector2Int TileAt(Vector2 point, Rect image, NavLayer layer)
{
int x = Mathf.FloorToInt((point.x - image.x) / image.width * layer.Width);
int y = layer.Height - 1 - Mathf.FloorToInt((point.y - image.y) / image.height * layer.Height);
return new Vector2Int(x, y);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 59dabb98180844c6a2fa998420d5c045
@@ -0,0 +1,295 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser
{
using System;
using System.Linq;
using Core.Contract.Constants;
using Core.DataReader.Lgt;
using Core.DataReader.Nav;
using Core.DataReader.Scn;
using Engine.Extensions;
using UnityEditor;
using UnityEngine;
public sealed partial class ResourceBrowserWindow
{
private readonly ResourceObjectView _objectView = new();
private string _recordQuery = "";
private int _recordIndex, _sceneRecordType;
private NavFile _sceneNav;
private bool _sceneLayout;
private Texture2D _navTexture;
private int _navLayer, _drawnNavLayer = -1;
private float _navZoom = 1;
private Vector2 _navPan;
private Vector2Int _navTile;
private void ClearSceneView()
{
_objectView.Reset();
_recordQuery = "";
_recordIndex = 0;
_sceneRecordType = 0;
_sceneNav = null;
_sceneLayout = false;
_navLayer = 0;
_drawnNavLayer = -1;
_navZoom = 1;
_navPan = Vector2.zero;
_navTile = Vector2Int.zero;
if (_navTexture != null)
DestroyImmediate(_navTexture);
_navTexture = null;
}
private void DrawResourceLink(string label, string path)
{
if (string.IsNullOrEmpty(path))
return;
ResourceEntry entry = _catalog.Find(path);
using (new EditorGUILayout.HorizontalScope())
{
using (new EditorGUI.DisabledScope(entry == null))
{
if (GUILayout.Button("Open " + label, GUILayout.Width(130)))
{
Select(entry);
GUIUtility.ExitGUI();
}
}
EditorGUILayout.SelectableLabel((entry == null ? "Missing: " : "") + path, GUILayout.Height(18));
}
}
private int PickRecord(string[] labels)
{
string query = EditorGUILayout.TextField("Find record", _recordQuery);
if (query != _recordQuery)
{
_recordQuery = query;
_recordIndex = 0;
_objectView.Reset();
}
int[] indices = Enumerable.Range(0, labels.Length).Where(i => labels[i].IndexOf(_recordQuery, StringComparison.OrdinalIgnoreCase) >= 0).ToArray();
if (indices.Length == 0)
{
EditorGUILayout.HelpBox("No matching records.", MessageType.Info);
return -1;
}
int current = Mathf.Max(0, Array.IndexOf(indices, _recordIndex));
int next = EditorGUILayout.Popup($"Record ({indices.Length:N0})", current, indices.Select(i => labels[i]).ToArray());
if (_recordIndex != indices[next])
_objectView.Reset();
_recordIndex = indices[next];
return _recordIndex;
}
private void DrawSceneView(ScnFile scene)
{
GUILayout.Label(scene.SceneInfo.ToString(), EditorStyles.wordWrappedLabel);
GUILayout.Label($"{scene.NpcInfos.Length} NPCs · {scene.ObjectInfos.Length} objects", EditorStyles.miniLabel);
DrawResourceLink("background", ResourceSceneData.BackgroundPath(scene.SceneInfo));
DrawResourceLink("navigation", FileConstants.GetNavFileVirtualPath(scene.SceneInfo.CityName, scene.SceneInfo.Model));
DrawResourceLink("script", FileConstants.GetSceneSceFileVirtualPath(scene.SceneInfo.CityName));
bool layout = GUILayout.Toggle(_sceneLayout, "Preview static layout", EditorStyles.miniButton);
if (layout != _sceneLayout)
{
_sceneLayout = layout;
if (layout)
CreateSceneLayout(scene);
else
{
_model?.Dispose();
_model = null;
}
}
if (_sceneLayout && _model != null)
{
if (GUILayout.Button("Frame layout"))
_model.Frame();
Rect rect = GUILayoutUtility.GetRect(100, 10000, 180, 260);
_model.Draw(rect);
DrawSceneMarkers(scene, rect);
if (Event.current.type is EventType.Used or EventType.MouseDrag or EventType.ScrollWheel)
Repaint();
}
int type = GUILayout.Toolbar(_sceneRecordType, new[] { "Scene", "NPCs", "Objects" });
if (type != _sceneRecordType)
{
_sceneRecordType = type;
_recordQuery = "";
_recordIndex = 0;
_objectView.Reset();
}
if (type == 0)
_objectView.Draw(scene.SceneInfo, DetailWidth);
else if (type == 1)
{
int index = PickRecord(scene.NpcInfos.Select(n => $"{n.Id} · {n.Name} · Script {n.ScriptId}").ToArray());
if (index >= 0)
{
OpenSceneScript(scene.SceneInfo.CityName, scene.NpcInfos[index].ScriptId);
_objectView.Draw(scene.NpcInfos[index], DetailWidth);
}
}
else
{
int index = PickRecord(scene.ObjectInfos.Select(o => $"{o.Id} · {o.Name} · {o.Type} · Script {o.ScriptId}").ToArray());
if (index >= 0)
{
OpenSceneScript(scene.SceneInfo.CityName, scene.ObjectInfos[index].ScriptId);
DrawResourceLink("object model", ResourceSceneData.ObjectPath(scene.SceneInfo, scene.ObjectInfos[index]));
_objectView.Draw(scene.ObjectInfos[index], DetailWidth);
}
}
}
private void CreateSceneLayout(ScnFile scene)
{
_model?.Dispose();
_model = new ResourceModelPreview(_catalog, _toon);
_sceneNav = null;
var errors = new System.Collections.Generic.List<string>();
try
{
ResourceEntry nav = _catalog.Find(FileConstants.GetNavFileVirtualPath(scene.SceneInfo.CityName, scene.SceneInfo.Model));
if (nav != null)
_sceneNav = (NavFile)ResourceFormats.Read(nav, _catalog.Read(nav), _catalog.Codepage);
}
catch (Exception ex) { errors.Add("Navigation: " + ex.Message); }
bool loadedBackground = false;
try
{
ResourceEntry background = _catalog.Find(ResourceSceneData.BackgroundPath(scene.SceneInfo));
if (background != null)
{
_model.Load(background, ResourceFormats.Read(background, _catalog.Read(background), _catalog.Codepage));
loadedBackground = true;
}
}
catch (Exception ex)
{
errors.Add("Background: " + ex.Message);
_model.Dispose();
_model = new ResourceModelPreview(_catalog, _toon);
}
if (!loadedBackground)
_model.FramePoints(scene.NpcInfos.Select(n => ResourceSceneData.NpcPosition(n, _sceneNav))
.Concat(scene.ObjectInfos.Select(o => o.GameBoxPosition.ToUnityPosition())));
if (errors.Count > 0)
_error = string.Join("\n", errors);
}
private void DrawSceneMarkers(ScnFile scene, Rect rect)
{
for (int i = 0; i < scene.NpcInfos.Length; i++)
DrawMarker(rect, ResourceSceneData.NpcPosition(scene.NpcInfos[i], _sceneNav), "N" + scene.NpcInfos[i].Id, 1, i, Color.cyan);
for (int i = 0; i < scene.ObjectInfos.Length; i++)
DrawMarker(rect, scene.ObjectInfos[i].GameBoxPosition.ToUnityPosition(), "O" + scene.ObjectInfos[i].Id, 2, i, Color.yellow);
}
private void DrawMarker(Rect rect, Vector3 position, string label, int type, int index, Color color)
{
if (!_model.Project(position, rect, out Vector2 point) || !rect.Contains(point))
return;
Color previous = GUI.color;
GUI.color = color;
if (GUI.Button(new Rect(point.x - 12, point.y - 8, 34, 18), label, EditorStyles.miniButton))
{
_sceneRecordType = type;
_recordIndex = index;
_recordQuery = "";
_objectView.Reset();
}
GUI.color = previous;
}
private void DrawNavigationView(NavFile nav)
{
if (nav.Layers.Length == 0)
{
EditorGUILayout.HelpBox("No navigation layers.", MessageType.Info);
return;
}
_navLayer = EditorGUILayout.Popup("Layer", _navLayer, Enumerable.Range(0, nav.Layers.Length).Select(i => "Layer " + i).ToArray());
NavLayer layer = nav.Layers[_navLayer];
if (layer.Width > SystemInfo.maxTextureSize || layer.Height > SystemInfo.maxTextureSize)
{
EditorGUILayout.HelpBox("Navigation dimensions exceed the GPU texture limit. Export the data for inspection.", MessageType.Warning);
return;
}
if (_navTexture == null || _drawnNavLayer != _navLayer)
{
if (_navTexture != null)
DestroyImmediate(_navTexture);
_navTexture = new Texture2D(layer.Width, layer.Height, TextureFormat.RGBA32, false)
{
hideFlags = HideFlags.HideAndDontSave,
filterMode = FilterMode.Point
};
_navTexture.SetPixels32(layer.Tiles.Select(ResourceSceneData.TileColor).ToArray());
_navTexture.Apply();
_drawnNavLayer = _navLayer;
_navTile = Vector2Int.zero;
_navPan = Vector2.zero;
}
GUILayout.Label($"{layer.Width} × {layer.Height} · Green: walkable · Red: obstacle · Gold: other blocked · Blue: portals", EditorStyles.wordWrappedMiniLabel);
GUILayout.Label("GameBox tile axes: X →, Z ↑ · Drag to pan · Wheel to zoom", EditorStyles.miniLabel);
Rect view = GUILayoutUtility.GetRect(100, 10000, 150, 10000, GUILayout.ExpandHeight(true));
GUI.BeginGroup(view);
float scale = Mathf.Min(view.width / layer.Width, view.height / layer.Height) * _navZoom;
Rect image = new((view.width - layer.Width * scale) / 2 + _navPan.x, (view.height - layer.Height * scale) / 2 + _navPan.y,
layer.Width * scale, layer.Height * scale);
GUI.DrawTexture(image, _navTexture, ScaleMode.StretchToFill, false);
foreach (var portal in layer.Portals.Where(p => !p.IsEmpty))
{
Rect area = new(image.x + portal.Left * scale, image.y + (layer.Height - 1 - portal.Bottom) * scale,
(portal.Right - portal.Left + 1) * scale, (portal.Bottom - portal.Top + 1) * scale);
EditorGUI.DrawRect(new Rect(area.x, area.y, area.width, 2), Color.cyan);
EditorGUI.DrawRect(new Rect(area.x, area.yMax - 2, area.width, 2), Color.cyan);
EditorGUI.DrawRect(new Rect(area.x, area.y, 2, area.height), Color.cyan);
EditorGUI.DrawRect(new Rect(area.xMax - 2, area.y, 2, area.height), Color.cyan);
}
Event e = Event.current;
if (new Rect(0, 0, view.width, view.height).Contains(e.mousePosition))
{
if (image.Contains(e.mousePosition) && e.type is EventType.MouseMove or EventType.MouseDown)
{
_navTile = ResourceSceneData.TileAt(e.mousePosition, image, layer);
Repaint();
}
if (e.type == EventType.MouseDrag)
{
_navPan += e.delta;
e.Use();
Repaint();
}
if (e.type == EventType.ScrollWheel)
{
_navZoom = Mathf.Clamp(_navZoom * Mathf.Exp(-e.delta.y * 0.06f), 0.5f, 24);
e.Use();
Repaint();
}
}
GUI.EndGroup();
_navTile.x = Mathf.Clamp(EditorGUILayout.IntField("Tile X", _navTile.x), 0, layer.Width - 1);
_navTile.y = Mathf.Clamp(EditorGUILayout.IntField("Tile Z", _navTile.y), 0, layer.Height - 1);
NavTile tile = layer.Tiles[_navTile.x + _navTile.y * layer.Width];
GUILayout.Label($"Height: {tile.GameBoxYPosition} GameBox units · Floor: {tile.FloorType} ({(int)tile.FloorType})", EditorStyles.wordWrappedLabel);
GUILayout.Label($"Walkable: {tile.IsWalkable()} · Obstacle: {tile.IsObstacle} · Obstacle distance: {tile.DistanceToNearestObstacle}");
var portalIndices = layer.Portals.Select((p, i) => (p, i)).Where(pair => !pair.p.IsEmpty && pair.p.IsPointInsideRect(_navTile.x, _navTile.y)).Select(pair => pair.i);
GUILayout.Label("Portals: " + string.Join(", ", portalIndices));
}
private void DrawLightView(LgtFile lights)
{
int index = PickRecord(lights.LightNodes.Select((light, i) => $"{i} · {light.LightType} · Radius {light.DecayRadius}").ToArray());
if (index >= 0)
_objectView.Draw(lights.LightNodes[index], DetailWidth);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ffcdd1fc6561431cac44e12a6f7fb0aa
@@ -0,0 +1,89 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Core.Command;
using Core.Command.SceCommands;
using Core.DataReader;
using Core.DataReader.Sce;
using Newtonsoft.Json;
public sealed class ResourceScriptLine
{
public long Offset;
public ushort Opcode, VariableMask;
public string Text, Dialogue;
public bool IsError;
}
public static class ResourceScriptListing
{
private static readonly Lazy<SceCommandParser> Parser = new(() =>
{
var resolver = new SceCommandTypeResolver();
resolver.Init();
return new SceCommandParser(resolver);
});
public static List<ResourceScriptLine> Decode(SceScriptBlock block, int codepage)
{
var lines = new List<ResourceScriptLine>();
using IBinaryReader reader = new SafeBinaryReader(block.ScriptData);
while (reader.Position < reader.Length)
{
var line = new ResourceScriptLine { Offset = reader.Position };
try
{
line.Opcode = reader.ReadUInt16();
line.VariableMask = reader.ReadUInt16();
reader.Seek(line.Offset, SeekOrigin.Begin);
ICommand command = Parser.Value.ParseNextCommand(reader, codepage, out _);
line.Dialogue = command switch
{
DialogueRenderTextCommand text => text.DialogueText,
DialogueRenderTextWithTimeLimitCommand timed => timed.DialogueText,
_ => null,
};
line.Text = $"{line.Offset:X6} op={line.Opcode} mask=0x{line.VariableMask:X4} {command.GetType().Name} {JsonConvert.SerializeObject(command)}";
}
catch (Exception ex)
{
line.IsError = true;
line.Text = $"{line.Offset:X6} ERROR in block {block.Id}: {ex.Message} (remaining bytes were not decoded)";
}
lines.Add(line);
if (line.IsError)
break;
}
return lines;
}
public static void Export(SceFile file, TextWriter writer, bool dialogueOnly)
{
writer.WriteLine("Decoded inspection listing. Offsets are block-relative; mask bits identify variable parameters. This is not compilable SCE source.");
foreach (var block in file.ScriptBlocks.Values.OrderBy(b => b.Id))
{
writer.WriteLine($"\nBLOCK {block.Id} · {block.Description}");
if (!dialogueOnly)
{
for (int i = 0; i < block.UserVariables.Length; i++)
writer.WriteLine($"LOCAL {i} type={block.UserVariables[i].Type} bytes={BitConverter.ToString(block.UserVariables[i].InitData)}");
}
foreach (ResourceScriptLine line in Decode(block, file.Codepage))
{
if (line.IsError || !dialogueOnly)
writer.WriteLine(line.Text);
else if (line.Dialogue != null)
writer.WriteLine($"{line.Offset:X6} {line.Dialogue}");
}
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 41368700554446a7b8500225aea10c53
@@ -0,0 +1,72 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser
{
using System;
using System.Text;
using System.IO;
using UnityEngine;
// Survives assembly reload through the owning window's serialized reference.
public sealed class ResourceTextDraft : ScriptableObject
{
public string Text, Original, SourcePath, PhysicalPath, SourceRoot;
public int Codepage;
public bool HasBom;
public bool IsDirty => Text != Original;
public bool Editable => Original != null && Original.Length <= 60000;
public void Load(byte[] bytes, int codepage)
{
int offset = 0;
Codepage = codepage;
HasBom = false;
if (bytes.Length >= 3 && bytes[0] == 0xef && bytes[1] == 0xbb && bytes[2] == 0xbf)
{
Codepage = 65001;
offset = 3;
}
else if (bytes.Length >= 2 && bytes[0] == 0xff && bytes[1] == 0xfe)
{
Codepage = 1200;
offset = 2;
}
else if (bytes.Length >= 2 && bytes[0] == 0xfe && bytes[1] == 0xff)
{
Codepage = 1201;
offset = 2;
}
HasBom = offset > 0;
Original = Text = StrictEncoding(Codepage).GetString(bytes, offset, bytes.Length - offset);
}
public bool CanReadFrom(string root) => !string.IsNullOrEmpty(SourceRoot) &&
Path.GetFullPath(SourceRoot).TrimEnd(Path.DirectorySeparatorChar).Equals(
Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar), StringComparison.OrdinalIgnoreCase);
public static string ContextAt(string text, int match)
{
int start = Math.Clamp(match - 40, 0, text.Length);
return text.Substring(start, Math.Min(180, text.Length - start));
}
public byte[] Encode(bool utf8)
{
Encoding encoding = StrictEncoding(utf8 ? 65001 : Codepage);
byte[] content = encoding.GetBytes(Text);
byte[] bom = !utf8 && HasBom ? encoding.GetPreamble() : Array.Empty<byte>();
if (bom.Length == 0)
return content;
var result = new byte[bom.Length + content.Length];
Buffer.BlockCopy(bom, 0, result, 0, bom.Length);
Buffer.BlockCopy(content, 0, result, bom.Length, content.Length);
return result;
}
private static Encoding StrictEncoding(int codepage) => Encoding.GetEncoding(codepage, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d1702ec8ac1d411ba1c57c6b4b5d7af9
@@ -0,0 +1,182 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser
{
using System;
using System.IO;
using UnityEditor;
using UnityEngine;
public sealed partial class ResourceBrowserWindow
{
[SerializeField] private ResourceTextDraft _textDraft;
private string _textFind = "";
private int _textPage, _textMatch = -1;
private bool _saveUtf8;
private void LoadText(ResourceEntry entry)
{
_textDraft = CreateInstance<ResourceTextDraft>();
_textDraft.hideFlags = HideFlags.HideInHierarchy | HideFlags.DontSave;
_textDraft.SourcePath = entry.Path;
_textDraft.PhysicalPath = entry.PhysicalPath;
_textDraft.SourceRoot = _catalog.Root;
_textDraft.Load(_bytes, _catalog.Codepage);
_textPage = 0;
_textMatch = -1;
_textFind = "";
_saveUtf8 = false;
UpdateTextDirty();
}
private void RestoreTextDraft()
{
if (_textDraft == null)
return;
ResourceEntry entry = _catalog != null && _textDraft.CanReadFrom(_catalog.Root)
? _catalog.Find(_textDraft.SourcePath) : null;
_selected = entry ?? new ResourceEntry(_textDraft.SourcePath, _textDraft.PhysicalPath);
UpdateTextDirty();
}
private void UpdateTextDirty()
{
_textMatch = -1;
hasUnsavedChanges = _textDraft != null && _textDraft.IsDirty;
Repaint();
}
private void DestroyTextDraft()
{
if (_textDraft != null)
{
Undo.ClearUndo(_textDraft);
DestroyImmediate(_textDraft);
}
_textDraft = null;
hasUnsavedChanges = false;
}
private bool CanReplaceSelection()
{
if (_textDraft == null || !_textDraft.IsDirty)
return true;
int choice = EditorUtility.DisplayDialogComplex("Unsaved text copy", "Save your edited text as a new file before leaving this resource?", "Save copy", "Cancel", "Discard");
return choice == 2 || choice == 0 && SaveTextCopy();
}
public override void SaveChanges()
{
if (SaveTextCopy())
base.SaveChanges();
}
public override void DiscardChanges()
{
if (_textDraft != null)
_textDraft.Text = _textDraft.Original;
base.DiscardChanges();
}
private void OnDestroy() => DestroyTextDraft();
private bool SaveTextCopy()
{
if (_textDraft == null)
return true;
string name = ResourceModelPreview.FileName(_textDraft.SourcePath);
string path = EditorUtility.SaveFilePanel("Save text copy (choose a new file)", "", Path.GetFileNameWithoutExtension(name) + ".edited", Path.GetExtension(name).TrimStart('.'));
if (path.Length == 0)
return false;
try
{
ResourceCatalog.CheckOutsideRoot(_textDraft.SourceRoot, path);
_catalog?.CheckExportDestination(path);
byte[] bytes = _textDraft.Encode(_saveUtf8);
ResourceCatalog.WriteNewFile(path, stream => stream.Write(bytes, 0, bytes.Length));
_textDraft.Original = _textDraft.Text;
UpdateTextDirty();
_status = "Saved text copy: " + path;
return true;
}
catch (Exception ex)
{
_error = ex.Message + " Choose UTF-8 if the source encoding cannot represent the edited characters.";
return false;
}
}
private void DrawTextView()
{
if (_textDraft == null || _textDraft.Text == null)
{
DrawHex();
return;
}
EditorGUILayout.SelectableLabel("Source: " + _textDraft.SourceRoot, EditorStyles.miniLabel, GUILayout.Height(20));
if (_catalog != null && !_textDraft.CanReadFrom(_catalog.Root))
EditorGUILayout.HelpBox("This draft belongs to another data folder. Save a text copy or choose a resource from the current catalog. Original export is disabled for this draft.", MessageType.Info);
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Label($"Encoding: {_textDraft.Codepage}{(_textDraft.HasBom ? " + BOM" : "")} · {_textDraft.Text.Length:N0} characters");
_saveUtf8 = GUILayout.Toggle(_saveUtf8, "Save as UTF-8", GUILayout.Width(110));
if (GUILayout.Button("Save copy…", GUILayout.Width(95)))
SaveTextCopy();
}
using (new EditorGUILayout.HorizontalScope())
{
string find = EditorGUILayout.TextField("Find", _textFind);
if (find != _textFind)
{
_textFind = find;
_textMatch = -1;
}
if (GUILayout.Button("Next", GUILayout.Width(50)) && _textFind.Length > 0)
{
_textMatch = _textDraft.Text.IndexOf(_textFind, Mathf.Clamp(_textMatch + 1, 0, _textDraft.Text.Length), StringComparison.OrdinalIgnoreCase);
if (_textMatch < 0)
_textMatch = _textDraft.Text.IndexOf(_textFind, StringComparison.OrdinalIgnoreCase);
if (_textMatch >= 0)
_textPage = _textMatch / 16000;
}
}
if (_textMatch >= 0 && _textFind.Length > 0)
EditorGUILayout.HelpBox($"Match at character {_textMatch}: " + ResourceTextDraft.ContextAt(_textDraft.Text, _textMatch), MessageType.Info);
if (!_textDraft.Editable)
{
EditorGUILayout.HelpBox("Large text is read-only and paged. Export the original to edit it externally.", MessageType.Info);
int pages = Mathf.Max(1, (_textDraft.Text.Length + 15999) / 16000);
_textPage = Mathf.Clamp(EditorGUILayout.IntField($"Page / {pages}", _textPage + 1) - 1, 0, pages - 1);
}
_detailScroll = EditorGUILayout.BeginScrollView(_detailScroll);
var style = new GUIStyle(EditorStyles.textArea) { wordWrap = true };
if (_textDraft.Editable)
{
float height = Mathf.Max(150, style.CalcHeight(new GUIContent(_textDraft.Text), Mathf.Max(100, DetailWidth - 30)));
string edited = EditorGUILayout.TextArea(_textDraft.Text, style, GUILayout.Height(height), GUILayout.ExpandWidth(true));
if (edited != _textDraft.Text)
{
if (edited.Length > 60000)
_error = "In-window text editing is limited to 60,000 characters. Export a copy for larger edits.";
else
{
Undo.RecordObject(_textDraft, "Edit resource text copy");
_textDraft.Text = edited;
UpdateTextDirty();
}
}
}
else
{
int start = _textPage * 16000;
string page = _textDraft.Text.Substring(start, Mathf.Min(16000, _textDraft.Text.Length - start));
float height = Mathf.Max(150, style.CalcHeight(new GUIContent(page), Mathf.Max(100, DetailWidth - 30)));
EditorGUILayout.SelectableLabel(page, style, GUILayout.Height(height), GUILayout.ExpandWidth(true));
}
EditorGUILayout.EndScrollView();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8f9f32b898b44d65b6b28f3aaf41160c
@@ -0,0 +1,78 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser
{
using System;
using System.IO;
using Engine.Core.Abstraction;
using Engine.Core.Implementation;
using Game.Data;
using UnityEditor;
using UnityEngine;
public sealed class ResourceTexturePreview : IDisposable
{
public Texture2D Texture
{
get; private set;
}
private UnityEditor.Editor _editor;
public ResourceTexturePreview(ResourceEntry entry, byte[] bytes)
{
try
{
bytes = ResourceImageData.Prepare(entry.Extension, bytes);
if (entry.Extension is ".png" or ".jpg" or ".jpeg")
{
Texture = new Texture2D(2, 2, TextureFormat.RGBA32, false);
if (!Texture.LoadImage(bytes))
throw new InvalidDataException("Unity could not decode this image.");
}
else
{
using ITextureDataSource source = new TextureLoaderFactory().GetTextureLoader(entry.Extension).Load(bytes, out _);
if ((long)source.Width * source.Height > 32 * 1024 * 1024)
throw new InvalidDataException("Image exceeds the 32 megapixel preview limit.");
Texture = (Texture2D)new UnityTextureFactory().CreateTexture(source, TextureCreateOptions.Readable).NativeObject;
}
Texture.name = entry.Name;
Texture.hideFlags = HideFlags.HideAndDontSave;
_editor = UnityEditor.Editor.CreateEditor(Texture);
}
catch
{
Dispose();
throw;
}
}
public void DrawSettings() => _editor?.OnPreviewSettings();
public void Draw(Rect rect)
{
if (_editor != null)
_editor.DrawPreview(rect);
}
public void SavePng(string path)
{
byte[] bytes = Texture.EncodeToPNG();
ResourceCatalog.WriteNewFile(path, stream => stream.Write(bytes, 0, bytes.Length));
}
public void Dispose()
{
if (_editor != null)
UnityEngine.Object.DestroyImmediate(_editor);
if (Texture != null)
UnityEngine.Object.DestroyImmediate(Texture);
_editor = null;
Texture = null;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0be49347d92342a18c6dd757e4a3bbab
@@ -178,6 +178,16 @@ namespace Pal3.Core.DataReader.Cpk
return _crcToTableEntityMap.ContainsKey(filePathCrcHash);
}
/// <summary>Read sizes from the index without allocating or decompressing file content.</summary>
public (long length, long packedLength) GetFileSizes(uint filePathCrcHash)
{
if (!_isInitialized)
throw new InvalidOperationException("Initialize the archive before accessing its content");
if (!_crcToTableEntityMap.TryGetValue(filePathCrcHash, out CpkTableEntity entry) || entry.IsDirectory())
throw new FileNotFoundException($"File entry not found: {filePathCrcHash}");
return (entry.IsCompressed() ? entry.OriginSize : entry.PackedSize, entry.PackedSize);
}
/// <summary>
/// Read all bytes of the give file stored inside the archive.
/// </summary>
@@ -115,6 +115,14 @@ namespace Pal3.Core.FileSystem
$"The file <{fileVirtualPath}> does not exist in any of the CPK archives");
}
/// <summary>Read uncompressed and stored sizes, including segmented archive resolution.</summary>
public (long length, long packedLength) GetFileSizes(string fileVirtualPath)
{
if (FileExistsInternal(fileVirtualPath, out uint crc, out string archive))
return _cpkArchives[archive].GetFileSizes(crc);
throw new FileNotFoundException(fileVirtualPath);
}
private bool FileExistsInternal(string fileVirtualPath,
out uint filePathCrcHash,
out string archiveName)
@@ -1,168 +0,0 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Game.Effect.Original
{
using System;
using UnityEngine;
// Runtime controls for ResourceViewer; editor tooling uses the same player.
public sealed class OriginalEffectViewer : MonoBehaviour
{
private static int _nextWindowId = 25000;
private readonly int _windowId = _nextWindowId++;
private OriginalEffectResources _resources;
private Transform _parent;
private Action _beforeLoad;
private OriginalEffectPlayer _player;
private OriginalPortalEffect _portal;
public uint PortalType
{
get; set;
}
private GameObject _root;
private string _id = "98", _diagnostics = "";
private Rect _window = new(15, 65, 330, 250);
private bool _visible;
public void Initialize(OriginalEffectResources resources, Transform parent, Action beforeLoad)
{
_resources = resources;
_parent = parent;
_beforeLoad = beforeLoad;
}
public void Load(int groupId)
{
Stop();
_beforeLoad?.Invoke();
_id = groupId.ToString();
_visible = true;
_diagnostics = "";
try
{
if (groupId < -1)
throw new ArgumentOutOfRangeException(nameof(groupId));
OriginalEffectOverrides edits = Resources.Load<OriginalEffectOverrides>(_resources.OverridesPath);
if (groupId >= 0)
{
_diagnostics = string.Join("\n", _resources.Diagnose(groupId, edits));
if (_diagnostics.Length > 0)
return;
}
_root = new GameObject(groupId < 0 ? "Original Transport" : $"Original {_resources.GameVariant} group {groupId}");
_root.transform.SetParent(_parent, false);
if (groupId < 0)
{
_portal = _root.AddComponent<OriginalPortalEffect>();
_portal.Initialize(_resources, PortalType);
}
else
{
_player = _root.AddComponent<OriginalEffectPlayer>();
_player.Initialize(_resources, groupId, overrides: edits);
_diagnostics += _player.Error;
}
}
catch (Exception ex)
{
_diagnostics = ex.Message;
Stop();
}
}
public void Stop()
{
if (_root != null)
{
_root.SetActive(false);
OriginalEffectResources.Destroy(_root);
}
_root = null;
_player = null;
_portal = null;
}
public void Seek(float time)
{
time = Mathf.Clamp(float.IsFinite(time) ? time : 0, 0, 600);
if (_player != null)
_player.Seek(time);
if (_portal != null)
_portal.Sample(time);
}
public void Pause(bool value)
{
if (_player != null)
_player.Paused = value;
if (_portal != null)
_portal.AutoAdvance = !value;
}
private void OnDisable() => Stop();
private void OnGUI()
{
if (_resources == null)
return;
if (GUI.Button(new Rect(Screen.width - 145, 15, 130, 32), $"Original {_resources.GameVariant} effects"))
_visible = !_visible;
if (_visible)
_window = GUI.Window(_windowId, _window, Draw, $"Original {_resources.GameVariant} effect viewer");
}
private void Draw(int id)
{
GUILayout.BeginHorizontal();
GUILayout.Label("Group", GUILayout.Width(45));
_id = GUILayout.TextField(_id);
if (GUILayout.Button("Load") && int.TryParse(_id, out int group))
Load(group);
if (GUILayout.Button("Transport"))
Load(-1);
GUILayout.EndHorizontal();
if (_portal != null && _resources.GameVariant == "PAL3A")
{
GUILayout.BeginHorizontal();
GUILayout.Label($"Transport style {PortalType}");
if (GUILayout.Button("Next style"))
{
PortalType = (PortalType + 1) % 7;
Load(-1);
}
GUILayout.EndHorizontal();
}
GUILayout.BeginHorizontal();
if (GUILayout.Button("Play"))
Pause(false);
if (GUILayout.Button("Pause"))
Pause(true);
if (GUILayout.Button("Reset"))
Seek(0);
if (GUILayout.Button("Stop"))
Stop();
GUILayout.EndHorizontal();
if (_player != null)
{
_player.Speed = GUILayout.HorizontalSlider(_player.Speed, 0, 4);
GUILayout.Label($"Speed {_player.Speed:0.00}x");
float time = GUILayout.HorizontalSlider(_player.Time, 0, Mathf.Max(30, _player.Time));
if (Mathf.Abs(time - _player.Time) > 0.001f)
{
Pause(true);
Seek(time);
}
GUILayout.Label($"{_player.Time:0.00}s objects {_player.NodeCount} quads/particles {_player.QuadCount}");
if (_player.Error != null)
GUILayout.Label(_player.Error);
}
GUILayout.Label(_diagnostics.Length == 0 ? "Original data / shared runtime" : _diagnostics);
GUI.DragWindow();
}
}
}
@@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: a67dbb1e7d0e340fe8b5dc4ca7bbecb5
@@ -522,70 +522,89 @@ namespace Pal3.Game.Rendering.Renderer
if (cancellationToken.IsCancellationRequested) yield break;
// Animates the mesh
for (int i = 0; i < _meshCount; i++)
{
RenderMeshComponent meshComponent = _renderMeshComponents[i];
uint[] frameTicks = _frameTicks[i];
int currentFrameIndex = CoreUtility.GetFloorIndex(frameTicks, tick);
uint currentFrameTick = _frameTicks[i][currentFrameIndex];
int nextFrameIndex = currentFrameIndex < frameTicks.Length - 1 ? currentFrameIndex + 1 : 0;
uint nextFrameTick = nextFrameIndex == 0 ? endTick : _frameTicks[i][nextFrameIndex];
float influence = (float)(tick - currentFrameTick) / (nextFrameTick - currentFrameTick);
Vector3[] vertices = meshComponent.MeshDataBuffer.VertexBuffer;
for (int j = 0; j < vertices.Length; j++)
{
vertices[j] = Vector3.Lerp(
_meshes[i].KeyFrames[currentFrameIndex].GameBoxVertices[j]
.ToUnityPosition(UnityPrimitivesConvertor.GameBoxMv3UnitToUnityUnit),
_meshes[i].KeyFrames[nextFrameIndex].GameBoxVertices[j]
.ToUnityPosition(UnityPrimitivesConvertor.GameBoxMv3UnitToUnityUnit), influence);
}
meshComponent.Mesh.SetVertices(vertices);
if (_materialManager.UsesToonRendering)
{
meshComponent.MeshDataBuffer.RebuildNormalsBySourceVertex(_meshes[i].NormalIndices, _sourceNormals[i]);
meshComponent.Mesh.SetNormals(meshComponent.MeshDataBuffer.NormalBuffer);
}
meshComponent.Mesh.RecalculateBounds();
}
// Animates the tag nodes
if (_tagNodePolFile != null)
{
for (int i = 0; i < _tagNodesInfo.Length; i++)
{
if (_tagNodes[i] == null) continue;
uint[] frameTicks = _tagNodeFrameTicks[i];
int currentFrameIndex = CoreUtility.GetFloorIndex(frameTicks, tick);
uint currentFrameTick = _tagNodeFrameTicks[i][currentFrameIndex];
int nextFrameIndex = currentFrameIndex < frameTicks.Length - 1 ? currentFrameIndex + 1 : 0;
uint nextFrameTick = nextFrameIndex == 0 ? endTick : _tagNodeFrameTicks[i][nextFrameIndex];
float influence = (float)(tick - currentFrameTick) / (nextFrameTick - currentFrameTick);
Vector3 position = Vector3.Lerp(
_tagNodesInfo[i].TagFrames[currentFrameIndex].GameBoxPosition.ToUnityPosition(),
_tagNodesInfo[i].TagFrames[nextFrameIndex].GameBoxPosition.ToUnityPosition(), influence);
Quaternion rotation = Quaternion.Slerp(
_tagNodesInfo[i].TagFrames[currentFrameIndex].GameBoxRotation.Mv3QuaternionToUnityQuaternion(),
_tagNodesInfo[i].TagFrames[nextFrameIndex].GameBoxRotation.Mv3QuaternionToUnityQuaternion(), influence);
_tagNodes[i].Transform.SetLocalPositionAndRotation(position, rotation);
}
}
SampleGeometry(tick, endTick);
yield return null;
}
}
/// <summary>Sample a pose without starting a coroutine, advancing game time, or dispatching events.</summary>
public void SampleAnimation(float seconds)
{
if (!IsInitialized)
throw new InvalidOperationException("Animation model not initialized");
if (!float.IsFinite(seconds))
throw new ArgumentOutOfRangeException(nameof(seconds));
uint tick = Mathf.Clamp(seconds, 0, (float)_totalGameBoxTicks / UnityPrimitivesConvertor.GameBoxTicksPerSecond).SecondsToGameBoxTick();
SampleGeometry(tick, _totalGameBoxTicks);
}
private void SampleGeometry(uint tick, uint endTick)
{
// Animates the mesh
for (int i = 0; i < _meshCount; i++)
{
RenderMeshComponent meshComponent = _renderMeshComponents[i];
uint[] frameTicks = _frameTicks[i];
int currentFrameIndex = Math.Max(0, CoreUtility.GetFloorIndex(frameTicks, tick));
uint currentFrameTick = _frameTicks[i][currentFrameIndex];
int nextFrameIndex = currentFrameIndex < frameTicks.Length - 1 ? currentFrameIndex + 1 : 0;
uint nextFrameTick = nextFrameIndex == 0 ? endTick : _frameTicks[i][nextFrameIndex];
float influence = nextFrameTick > currentFrameTick
? Mathf.Clamp01(((float)tick - currentFrameTick) / (nextFrameTick - currentFrameTick)) : 0;
Vector3[] vertices = meshComponent.MeshDataBuffer.VertexBuffer;
for (int j = 0; j < vertices.Length; j++)
{
vertices[j] = Vector3.Lerp(
_meshes[i].KeyFrames[currentFrameIndex].GameBoxVertices[j]
.ToUnityPosition(UnityPrimitivesConvertor.GameBoxMv3UnitToUnityUnit),
_meshes[i].KeyFrames[nextFrameIndex].GameBoxVertices[j]
.ToUnityPosition(UnityPrimitivesConvertor.GameBoxMv3UnitToUnityUnit), influence);
}
meshComponent.Mesh.SetVertices(vertices);
if (_materialManager.UsesToonRendering)
{
meshComponent.MeshDataBuffer.RebuildNormalsBySourceVertex(_meshes[i].NormalIndices, _sourceNormals[i]);
meshComponent.Mesh.SetNormals(meshComponent.MeshDataBuffer.NormalBuffer);
}
meshComponent.Mesh.RecalculateBounds();
}
// Animates the tag nodes
if (_tagNodePolFile != null)
{
for (int i = 0; i < _tagNodesInfo.Length; i++)
{
if (_tagNodes[i] == null)
continue;
uint[] frameTicks = _tagNodeFrameTicks[i];
int currentFrameIndex = Math.Max(0, CoreUtility.GetFloorIndex(frameTicks, tick));
uint currentFrameTick = _tagNodeFrameTicks[i][currentFrameIndex];
int nextFrameIndex = currentFrameIndex < frameTicks.Length - 1 ? currentFrameIndex + 1 : 0;
uint nextFrameTick = nextFrameIndex == 0 ? endTick : _tagNodeFrameTicks[i][nextFrameIndex];
float influence = nextFrameTick > currentFrameTick
? Mathf.Clamp01(((float)tick - currentFrameTick) / (nextFrameTick - currentFrameTick)) : 0;
Vector3 position = Vector3.Lerp(
_tagNodesInfo[i].TagFrames[currentFrameIndex].GameBoxPosition.ToUnityPosition(),
_tagNodesInfo[i].TagFrames[nextFrameIndex].GameBoxPosition.ToUnityPosition(), influence);
Quaternion rotation = Quaternion.Slerp(
_tagNodesInfo[i].TagFrames[currentFrameIndex].GameBoxRotation.Mv3QuaternionToUnityQuaternion(),
_tagNodesInfo[i].TagFrames[nextFrameIndex].GameBoxRotation.Mv3QuaternionToUnityQuaternion(), influence);
_tagNodes[i].Transform.SetLocalPositionAndRotation(position, rotation);
}
}
}
public bool IsVisibleToCamera()
{
if (!IsInitialized) return false;
@@ -48,11 +48,6 @@ namespace Pal3.Game.Rendering.Renderer
private List<(IMaterial[] materials, ITexture2D firstFrame)> _waterSurfaces;
private UnityEngine.Coroutine _waterAnimation;
protected override void OnEnableGameEntity()
{
_textureFactory = ServiceLocator.Instance.Get<ITextureFactory>();
}
protected override void OnDisableGameEntity()
{
Dispose();
@@ -63,8 +58,11 @@ namespace Pal3.Game.Rendering.Renderer
IMaterialManager materialManager,
bool isStaticObject,
Color? tintColor = default,
bool forceOpaqueWater = false)
bool forceOpaqueWater = false,
ITextureFactory textureFactory = null,
bool animateWater = true)
{
_textureFactory = textureFactory ?? ServiceLocator.Instance.Get<ITextureFactory>();
_textureProvider = textureProvider;
_materialManager = materialManager;
_isStaticObject = isStaticObject;
@@ -80,7 +78,7 @@ namespace Pal3.Game.Rendering.Renderer
foreach (var entry in batches)
RenderGeometry("POL " + entry.Key.cell, entry.Value, entry.Key.materials);
if (_waterSurfaces != null)
if (animateWater && _waterSurfaces != null)
{
_waterAnimation = StartCoroutine(AnimateWaterTextures());
}
@@ -153,6 +153,22 @@ namespace Pal3.Game.Rendering.Renderer
StartCoroutine(PlayAnimationInternalAsync(loopCount, _animationCts.Token));
}
/// <summary>Sample a pose in seconds without starting playback or changing the game clock.</summary>
public void SampleAnimation(MovFile animation, float seconds)
{
if (!IsInitialized)
throw new InvalidOperationException("Animation model not initialized");
if (animation == null)
throw new ArgumentNullException(nameof(animation));
if (!float.IsFinite(seconds))
throw new ArgumentOutOfRangeException(nameof(seconds));
if (!ReferenceEquals(_movFile, animation))
SetupAnimationTrack(animation);
uint tick = Mathf.Clamp(seconds, 0, _movFile.Duration).SecondsToGameBoxTick();
UpdateBone(_bones[0], tick);
UpdateSkinning();
}
public void PauseAnimation()
{
if (_animationCts is {IsCancellationRequested: false})
@@ -253,16 +269,13 @@ namespace Pal3.Game.Rendering.Renderer
if (track != null)
{
int currentFrameIndex = CoreUtility.GetFloorIndex(bone.FrameTicks, tick);
int currentFrameIndex = Math.Max(0, CoreUtility.GetFloorIndex(bone.FrameTicks, tick));
uint currentFrameTick = bone.FrameTicks[currentFrameIndex];
int nextFrameIndex = currentFrameIndex < bone.FrameTicks.Length - 1 ? currentFrameIndex + 1 : 0;
uint nextFrameTick = bone.FrameTicks[nextFrameIndex];
float influence = 1f;
if (nextFrameTick != currentFrameTick)
{
influence = (float)(tick - currentFrameTick) / (nextFrameTick - currentFrameTick);
}
float influence = nextFrameTick > currentFrameTick
? Mathf.Clamp01(((float)tick - currentFrameTick) / (nextFrameTick - currentFrameTick)) : 0;
Vector3 localPosition = Vector3.Lerp(
track.Value.KeyFrames[currentFrameIndex].GameBoxTranslation.ToUnityPosition(),
@@ -8,7 +8,7 @@ namespace Pal3.Game.Settings
using System;
using UnityEngine.Rendering.Universal;
// Game and ResourceViewer apply the saved setting during their respective scenes.
// Applies the saved game setting and restores the pipeline asset when disposed.
public sealed class MultisampleAntiAliasing : IDisposable
{
private readonly UniversalRenderPipelineAsset _pipeline;
-3
View File
@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: 8dd6d2a4ee924fc0bc77c57c04ed67f8
timeCreated: 1641725553
@@ -1,188 +0,0 @@
// ------------------------------------------------------------------------
// Copyright (c) 2021-2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceViewer
{
using IngameDebugConsole;
using UnityEngine;
using UnityEngine.InputSystem;
/// <summary>
/// A simple free camera to be added to a Unity game object.
///
/// Keys:
/// wasd / arrows - movement
/// q/e - up/down (local space)
/// r/f - up/down (world space)
/// pageup/pagedown - up/down (world space)
/// hold shift - enable fast movement mode
/// right mouse - enable free look
/// mouse - free look / rotation
///
/// </summary>
public class FreeCameraController : MonoBehaviour
{
/// <summary>
/// Normal speed of camera movement.
/// </summary>
public float movementSpeed = 20f;
/// <summary>
/// Speed of camera movement when shift is held down,
/// </summary>
public float fastMovementSpeed = 100f;
/// <summary>
/// Sensitivity for free look.
/// </summary>
public float freeLookSensitivity = 0.1f;
/// <summary>
/// Amount to zoom the camera when using the mouse wheel.
/// </summary>
public float zoomSensitivity = 0.1f;
/// <summary>
/// Set to true when free looking (on right mouse button).
/// </summary>
private bool _looking = false;
private bool _lookingStarted = false;
private bool _enable = true;
private void OnEnable()
{
DebugLogManager.Instance.OnLogWindowShown += OnDebugWindowShown;
DebugLogManager.Instance.OnLogWindowHidden += OnDebugWindowHidden;
}
private void OnDisable()
{
DebugLogManager.Instance.OnLogWindowShown -= OnDebugWindowShown;
DebugLogManager.Instance.OnLogWindowHidden -= OnDebugWindowHidden;
StopLooking();
}
private void OnDebugWindowShown()
{
StopLooking();
_enable = false;
}
private void OnDebugWindowHidden()
{
_enable = true;
}
private void Update()
{
if (!_enable) return;
var fastMode = Keyboard.current.leftShiftKey.isPressed||
Keyboard.current.rightShiftKey.isPressed;
var movementSpeed = fastMode ? fastMovementSpeed : this.movementSpeed;
if (Keyboard.current.aKey.isPressed ||
Keyboard.current.leftArrowKey.isPressed)
{
transform.position += (-transform.right * movementSpeed * Time.deltaTime);
}
if (Keyboard.current.dKey.isPressed ||
Keyboard.current.rightArrowKey.isPressed)
{
transform.position += (transform.right * movementSpeed * Time.deltaTime);
}
if (Keyboard.current.wKey.isPressed ||
Keyboard.current.upArrowKey.isPressed)
{
transform.position += (transform.forward * movementSpeed * Time.deltaTime);
}
if (Keyboard.current.sKey.isPressed ||
Keyboard.current.downArrowKey.isPressed)
{
transform.position += (-transform.forward * movementSpeed * Time.deltaTime);
}
if (Keyboard.current.qKey.isPressed)
{
transform.position += (transform.up * movementSpeed * Time.deltaTime);
}
if (Keyboard.current.eKey.isPressed)
{
transform.position += (-transform.up * movementSpeed * Time.deltaTime);
}
if (Keyboard.current.rKey.isPressed ||
Keyboard.current.pageUpKey.isPressed)
{
transform.position += (Vector3.up * movementSpeed * Time.deltaTime);
}
if (Keyboard.current.fKey.isPressed ||
Keyboard.current.pageDownKey.isPressed)
{
transform.position += (-Vector3.up * movementSpeed * Time.deltaTime);
}
float yAxis = Mouse.current.scroll.y.ReadValue();
if (yAxis != 0)
{
transform.position += transform.forward * yAxis * this.zoomSensitivity;
}
if (_looking)
{
Vector2 delta = Mouse.current.delta.ReadValue();
if (delta.x != 0 || delta.y != 0)
{
if (!_lookingStarted)
{
_lookingStarted = true; // This is to fix a bug on MacOS
}
else
{
float newRotationX = transform.localEulerAngles.y + delta.x * freeLookSensitivity;
float newRotationY = transform.localEulerAngles.x - delta.y * freeLookSensitivity;
transform.localEulerAngles = new Vector3(newRotationY, newRotationX, 0f);
}
}
}
if (Mouse.current.rightButton.wasPressedThisFrame)
{
StartLooking();
}
else if (Mouse.current.rightButton.wasReleasedThisFrame)
{
StopLooking();
}
}
/// <summary>
/// Enable free looking.
/// </summary>
private void StartLooking()
{
_looking = true;
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
/// <summary>
/// Disable free looking.
/// </summary>
private void StopLooking()
{
_looking = false;
_lookingStarted = false;
Cursor.visible = true;
Cursor.lockState = CursorLockMode.None;
}
}
}
@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: bd5057af93f24311a4c6091099aa622d
timeCreated: 1641489169
@@ -1,861 +0,0 @@
// ------------------------------------------------------------------------
// Copyright (c) 2021-2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceViewer
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Core.Command;
using Core.Command.SceCommands;
using Core.Contract.Constants;
using Core.DataReader;
using Core.DataReader.Cpk;
using Core.DataReader.Cvd;
using Core.DataReader.Mov;
using Core.DataReader.Msh;
using Core.DataReader.Mtl;
using Core.DataReader.Mv3;
using Core.DataReader.Pol;
using Core.DataReader.Sce;
using Core.FileSystem;
using Core.Utilities;
using Engine.Core.Abstraction;
using Engine.Extensions;
using Engine.Logging;
using Engine.Services;
using Engine.Utilities;
using Game.Constants;
using Game.Effect.Original;
using Game.Data;
using Game.Rendering.Toon;
using Game.Rendering.Renderer;
using Game.Settings;
using IngameDebugConsole;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using TMPro;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
using Random = System.Random;
using Color = Core.Primitives.Color;
/// <summary>
/// The PAL3/PAL3A Game Resource Viewer app model
/// </summary>
public sealed class GameResourceViewer : MonoBehaviour
{
[SerializeField] private TextMeshProUGUI consoleTextUI;
[SerializeField] private TextMeshProUGUI nowPlayingTextUI;
[SerializeField] private TextMeshProUGUI fpsTextUI;
[SerializeField] private Button randomPolButton;
[SerializeField] private Button randomCvdButton;
[SerializeField] private Button randomMv3Button;
[SerializeField] private Button randomMp3Button;
[SerializeField] private Button randomMovButton;
[SerializeField] private Button extractAllCpkFilesButton;
[SerializeField] private AudioSource audioSource;
[SerializeField] private FpsCounter fpsCounter;
private OriginalEffectViewer _effectViewer;
private ICpkFileSystem _fileSystem;
private GameResourceProvider _resourceProvider;
private GameSettings _gameSettings;
private ISceCommandParser _sceCommandParser;
private IList<string> _polFiles;
private IList<string> _cvdFiles;
private IList<string> _mv3Files;
private IList<string> _movFiles;
private IList<string> _mp3Files;
private static readonly Random Random = new();
private GameObject _renderingRoot;
private Light _previewKey;
private ToonCameraLighting _toonCameraLighting;
private MultisampleAntiAliasing _antiAliasing;
private int _codePage;
//private HashSet<char> _charSet;
private void OnEnable()
{
ServiceLocator.Instance.Register<IGameTimeProvider>(GameTimeProvider.Instance);
_gameSettings = ServiceLocator.Instance.Get<GameSettings>();
_gameSettings.OnGameSettingsChanged += OnRenderingSettingsChanged;
_antiAliasing = new MultisampleAntiAliasing(_gameSettings.AntiAliasing);
_codePage = _gameSettings.Language == Language.SimplifiedChinese ? 936 : 950;
_fileSystem = ServiceLocator.Instance.Get<ICpkFileSystem>();
_resourceProvider = ServiceLocator.Instance.Get<GameResourceProvider>();
_sceCommandParser = ServiceLocator.Instance.Get<ISceCommandParser>();
_renderingRoot = new GameObject("Model");
_renderingRoot.transform.SetParent(null);
_effectViewer = GetComponent<OriginalEffectViewer>() ?? gameObject.AddComponent<OriginalEffectViewer>();
_effectViewer.enabled = true;
_effectViewer.Initialize(_resourceProvider.OriginalEffects, _renderingRoot.transform, DestroyExistingRenderingObjects);
DebugLogConsole.AddCommand<int>("Effect.Load", "Play an original flexeff group (-1: transport point).", _effectViewer.Load);
DebugLogConsole.AddCommand<float>("Effect.Seek", "Reset and resimulate the original effect to a time.", _effectViewer.Seek);
DebugLogConsole.AddCommand<bool>("Effect.Pause", "Pause or resume the original effect.", _effectViewer.Pause);
#if UNITY_2022_1_OR_NEWER
int monitorRefreshRate = (int)Screen.currentResolution.refreshRateRatio.value;
#else
var monitorRefreshRate = Screen.currentResolution.refreshRate;
#endif
if (Application.platform is RuntimePlatform.IPhonePlayer or RuntimePlatform.Android)
{
DebugLogManager.Instance.PopupEnabled = true;
}
if (_resourceProvider.GetMaterialManager().UsesToonRendering)
{
_previewKey ??= ToonLighting.CreateKey(transform, Quaternion.Euler(40f, -35f, 0f),
new UnityEngine.Color(1f, 0.97f, 0.94f), 1f);
ToonLighting.ConfigureKeyShadows(_previewKey, _gameSettings);
_previewKey.enabled = true;
if (Camera.main is { } camera)
{
_toonCameraLighting = ToonCameraLighting.Attach(camera, _gameSettings);
}
}
IDictionary<string, IList<string>> searchResults =
_fileSystem.BatchSearch(new[] { ".pol", ".cvd", ".mv3", ".mov", ".mp3" });
_polFiles = searchResults[".pol"];
_cvdFiles = searchResults[".cvd"];
_mv3Files = searchResults[".mv3"];
_movFiles = searchResults[".mov"];
_mp3Files = searchResults[".mp3"];
randomPolButton.onClick.AddListener(RandPol);
randomCvdButton.onClick.AddListener(RandCvd);
randomMv3Button.onClick.AddListener(RandMv3);
randomMovButton.onClick.AddListener(RandMov);
randomMp3Button.onClick.AddListener(RandMp3);
#if UNITY_EDITOR
extractAllCpkFilesButton.onClick.AddListener(ExtractAllCpkArchives);
#else
extractAllCpkFilesButton.interactable = false;
#endif
DebugLogConsole.AddCommand<string>("Search", "Search files using keyword.", Search);
DebugLogConsole.AddCommand<string, bool>("Load", "Load a file to the viewer (.pol, .cvd, .mp3 or .mv3).", Load);
#if UNITY_EDITOR
DebugLogConsole.AddCommand("DecompileAllSceScripts",
"Decompile all .sce scripts into txt format.",
() => DecompileAllSceScripts(dialogueOnly: false));
DebugLogConsole.AddCommand("DecompileAllDialogues",
"Decompile all dialogues in .sce scripts into txt format.",
() => DecompileAllSceScripts(dialogueOnly: true));
DebugLogConsole.AddCommand("ExtractAllCpkArchives",
"Extract all .cpk archives into the output directory.",
ExtractAllCpkArchives);
DebugLogConsole.AddCommand("ExportAllGdbFiles",
"Export all .gdb files into the output directory.",
ExportAllGdbFiles);
#endif
//__Malicious__Dev_Only__();
}
private void __Malicious__Dev_Only__()
{
// var objectInfoDic = new Dictionary<ScnSceneObjectType, HashSet<ScnFile>>();
// var sb = new StringBuilder();
//
// foreach (ScnSceneObjectType objectType in Enum.GetValues(typeof(ScnSceneObjectType)).Cast<ScnSceneObjectType>())
// {
// objectInfoDic[objectType] = new HashSet<ScnFile>();
// }
//
// var scnFilePaths = _fileSystem.Search(".scn").ToList();
// scnFilePaths.Sort();
//
// foreach (var scnFilePath in scnFilePaths)
// {
// ScnFile scnFile = _resourceProvider.GetGameResourceFile<ScnFile>(scnFilePath);
//
// foreach (ScnSceneObjectType objectType in Enum.GetValues(typeof(ScnSceneObjectType)).Cast<ScnSceneObjectType>())
// {
// if (scnFile.ObjectInfos.Any(_ => _.Type == objectType))
// {
// objectInfoDic[objectType].Add(scnFile);
// }
// }
// }
//
// // Print objectInfoDic to console
// foreach (var (objectType, scnFiles) in objectInfoDic)
// {
// sb.Append($"{objectType}:");
// foreach (var scnFile in scnFiles)
// {
// sb.Append($" {scnFile.SceneInfo.CityName}-{scnFile.SceneInfo.SceneName}");
// }
// sb.Append("\n");
// }
//
// EngineLogger.Log(sb.ToString());
}
private void OnRenderingSettingsChanged(string propertyName)
{
if (propertyName == nameof(GameSettings.AntiAliasing))
_antiAliasing?.Apply(_gameSettings.AntiAliasing);
if (_previewKey != null)
ToonLighting.ConfigureKeyShadows(_previewKey, _gameSettings);
}
private void OnDisable()
{
if (_effectViewer != null)
_effectViewer.enabled = false;
DebugLogConsole.RemoveCommand("Effect.Load");
DebugLogConsole.RemoveCommand("Effect.Seek");
DebugLogConsole.RemoveCommand("Effect.Pause");
if (_gameSettings != null)
_gameSettings.OnGameSettingsChanged -= OnRenderingSettingsChanged;
_antiAliasing?.Dispose();
_toonCameraLighting?.Detach();
if (_previewKey != null)
_previewKey.enabled = false;
}
private void Update()
{
GameTimeProvider.Instance.Tick(Time.deltaTime);
fpsTextUI.text = $"{Mathf.Ceil(fpsCounter.GetFps())} fps";
}
private void RandPol()
{
while (!LoadPol(_polFiles[Random.Next(0, _polFiles.Count)]))
{
}
}
private void RandCvd()
{
while (!LoadCvd(_cvdFiles[Random.Next(0, _cvdFiles.Count)]))
{
}
}
private void RandMv3()
{
while (!LoadMv3(_mv3Files[Random.Next(0, _mv3Files.Count)]))
{
}
}
private void RandMov()
{
while (!LoadMov(_movFiles[Random.Next(0, _movFiles.Count)]))
{
}
}
private void RandMp3()
{
while (!LoadMp3(_mp3Files[Random.Next(0, _mp3Files.Count)]))
{
}
}
private void Search(string keyword)
{
foreach (var result in _fileSystem.Search(keyword))
{
EngineLogger.Log(result);
}
}
private bool Load(string filePath)
{
if (!_fileSystem.FileExists(filePath))
{
EngineLogger.LogError($"{filePath} does not exists.");
return false;
}
string ext = Path.GetExtension(filePath).ToLower();
return ext switch
{
".pol" => LoadPol(filePath),
".cvd" => LoadCvd(filePath),
".mv3" => LoadMv3(filePath),
".mov" => LoadMov(filePath),
".mp3" => LoadMp3(filePath),
_ => throw new Exception($"File extension: <{ext}> not supported.")
};
}
private bool LoadPol(string filePath)
{
DestroyExistingRenderingObjects();
consoleTextUI.text = $"Loading: {filePath}";
EngineLogger.Log($"Loading: {filePath}");
try
{
PolFile polyFile = _resourceProvider.GetGameResourceFile<PolFile>(filePath);
ITextureResourceProvider textureProvider = _resourceProvider.CreateTextureResourceProvider(
CoreUtility.GetDirectoryName(filePath, CpkConstants.DirectorySeparatorChar));
GameObject mesh = new(CoreUtility.GetFileName(filePath, CpkConstants.DirectorySeparatorChar));
PolyModelRenderer meshRenderer = mesh.AddComponent<PolyModelRenderer>();
mesh.transform.SetParent(_renderingRoot.transform);
meshRenderer.Render(polyFile,
textureProvider,
_resourceProvider.GetMaterialManager(),
isStaticObject: true,
Color.White);
consoleTextUI.text = $"{filePath}";
Camera.main!.transform.LookAt(new Vector3(0, 0, 0));
return true;
}
catch (Exception ex)
{
EngineLogger.LogException(ex);
consoleTextUI.text = $"Failed to load: {filePath}";
return false;
}
}
private bool LoadCvd(string filePath)
{
DestroyExistingRenderingObjects();
consoleTextUI.text = $"Loading: {filePath}";
EngineLogger.Log($"Loading: {filePath}");
try
{
CvdFile cvdFile = _resourceProvider.GetGameResourceFile<CvdFile>(filePath);
ITextureResourceProvider textureProvider = _resourceProvider.CreateTextureResourceProvider(
CoreUtility.GetDirectoryName(filePath, CpkConstants.DirectorySeparatorChar));
GameObject animationNode = new(CoreUtility.GetFileName(filePath, CpkConstants.DirectorySeparatorChar));
CvdModelRenderer meshRenderer = animationNode.AddComponent<CvdModelRenderer>();
animationNode.transform.SetParent(_renderingRoot.transform);
meshRenderer.Init(cvdFile,
textureProvider,
_resourceProvider.GetMaterialManager());
meshRenderer.LoopAnimation();
consoleTextUI.text = $"{filePath}";
Camera.main!.transform.LookAt(new Vector3(0, 0, 0));
return true;
}
catch (Exception ex)
{
EngineLogger.LogException(ex);
consoleTextUI.text = $"Failed to load: {filePath}";
return false;
}
}
private bool LoadMv3(string filePath)
{
DestroyExistingRenderingObjects();
consoleTextUI.text = $"Loading: {filePath}";
EngineLogger.Log($"Loading: {filePath}");
try
{
Mv3File mv3File = _resourceProvider.GetGameResourceFile<Mv3File>(filePath);
ITextureResourceProvider textureProvider = _resourceProvider.CreateTextureResourceProvider(
CoreUtility.GetDirectoryName(filePath, CpkConstants.DirectorySeparatorChar));
if (mv3File.Meshes.Length > 1)
{
EngineLogger.LogWarning($"{filePath} has {mv3File.Meshes.Length} meshes.");
}
GameObject animationNode = new GameObject(CoreUtility.GetFileName(filePath, CpkConstants.DirectorySeparatorChar));
animationNode.transform.SetParent(_renderingRoot.transform);
Mv3ModelRenderer mv3AnimationRenderer = animationNode.AddComponent<Mv3ModelRenderer>();
//For debugging tag node:
// if (mv3File.TagNodes is {Length: > 0} &&
// !mv3File.TagNodes[0].Name.Equals("tag_weapon3", StringComparison.OrdinalIgnoreCase) &&
// filePath.Contains(@"ROLE\101"))
// {
// var weaponName = "JT13";
//
// var weaponPath = FileConstants.GetWeaponModelFileVirtualPath(weaponName);
//
// PolFile polFile = _resourceProvider.GetGameResourceFile<PolFile>(weaponPath);
// ITextureResourceProvider weaponTextureProvider = _resourceProvider.CreateTextureResourceProvider(
// CoreUtility.GetRelativeDirectoryPath(weaponPath));
// mv3AnimationRenderer.Init(mv3File,
// _resourceProvider.GetMaterialManager(),
// textureProvider,
// Color.white,
// polFile,
// weaponTextureProvider);
// }
// else
{
mv3AnimationRenderer.Init(mv3File,
_resourceProvider.GetMaterialManager(),
textureProvider);
}
mv3AnimationRenderer.StartAnimation();
consoleTextUI.text = $"{filePath}";
Camera.main!.transform.LookAt(new Vector3(0, 2, 0));
return true;
}
catch (Exception ex)
{
EngineLogger.LogException(ex);
consoleTextUI.text = $"Failed to load: {filePath}";
return false;
}
}
private bool LoadMov(string filePath)
{
DestroyExistingRenderingObjects();
consoleTextUI.text = $"Loading: {filePath}";
EngineLogger.Log($"Loading: {filePath}");
try
{
string actorFolderPath = CoreUtility.GetDirectoryName(filePath, CpkConstants.DirectorySeparatorChar);
string actorName = CoreUtility.GetFileName(actorFolderPath, CpkConstants.DirectorySeparatorChar);
string mshFilePath = filePath.Replace(".mov", ".msh", StringComparison.OrdinalIgnoreCase);
if (!_fileSystem.FileExists(mshFilePath))
{
mshFilePath = actorFolderPath + CpkConstants.DirectorySeparatorChar + actorName + ".msh";
}
MshFile mshFile = _resourceProvider.GetGameResourceFile<MshFile>(mshFilePath);
string mtlFilePath = actorFolderPath + CpkConstants.DirectorySeparatorChar + actorName + ".mtl";
MtlFile mtlFile = _resourceProvider.GetGameResourceFile<MtlFile>(mtlFilePath);
MovFile movFile = _resourceProvider.GetGameResourceFile<MovFile>(filePath);
ITextureResourceProvider textureProvider = _resourceProvider.CreateTextureResourceProvider(
CoreUtility.GetDirectoryName(mtlFilePath, CpkConstants.DirectorySeparatorChar));
GameObject animationNode = new(CoreUtility.GetFileName(filePath, CpkConstants.DirectorySeparatorChar));
animationNode.transform.SetParent(_renderingRoot.transform);
SkeletalModelRenderer skeletalModelRenderer = animationNode.AddComponent<SkeletalModelRenderer>();
skeletalModelRenderer.Init(mshFile,
mtlFile,
_resourceProvider.GetMaterialManager(),
textureProvider);
skeletalModelRenderer.StartAnimation(movFile);
consoleTextUI.text = $"{filePath}";
Camera.main!.transform.LookAt(new Vector3(0, 2, 0));
return true;
}
catch (Exception ex)
{
EngineLogger.LogException(ex);
consoleTextUI.text = $"Failed to load: {filePath}";
return false;
}
}
#if UNITY_EDITOR
private void DecompileAllSceScripts(bool dialogueOnly)
{
IEnumerable<string> sceFiles = _fileSystem.Search(".sce")
.Where(_ => !_.Contains(".bak", StringComparison.OrdinalIgnoreCase));
string title = dialogueOnly ? "选择脚本导出目录(仅对话)" : "选择脚本导出目录";
string outputFolderPath = EditorUtility.SaveFolderPanel(title, "", "");
if (string.IsNullOrWhiteSpace(outputFolderPath))
return;
outputFolderPath += $"{Path.DirectorySeparatorChar}{GameConstants.AppName}" + (dialogueOnly ? "_对话脚本" : "");
if (!Directory.Exists(outputFolderPath))
{
Directory.CreateDirectory(outputFolderPath);
}
foreach (string sceFile in sceFiles)
if (!DecompileSce(sceFile, outputFolderPath, dialogueOnly))
break;
// _charSet = new HashSet<char>();
// foreach (var itemInfo in _resourceProvider.GetGameItemInfos().Values)
// {
// foreach (var ch in itemInfo.Name) _charSet.Add(ch);
// foreach (var ch in itemInfo.Description) _charSet.Add(ch);
// }
//
// foreach (var actorInfo in _resourceProvider.GetCombatActorInfos().Values)
// {
// foreach (var ch in actorInfo.Name) _charSet.Add(ch);
// foreach (var ch in actorInfo.Description) _charSet.Add(ch);
// }
//
// foreach (var skillInfo in _resourceProvider.GetSkillInfos().Values)
// {
// foreach (var ch in skillInfo.Name) _charSet.Add(ch);
// foreach (var ch in skillInfo.Description) _charSet.Add(ch);
// }
//
// foreach (var comboSkillInfo in _resourceProvider.GetComboSkillInfos().Values)
// {
// foreach (var ch in comboSkillInfo.Name) _charSet.Add(ch);
// foreach (var ch in comboSkillInfo.Description) _charSet.Add(ch);
// }
//
// #if PAL3A
// var taskDefinitionFile = _resourceProvider.GetGameResourceFile<TaskDefinitionFile>(
// FileConstants.DataScriptFolderVirtualPath + "task.txt");
// foreach (Task task in taskDefinitionFile.Tasks)
// {
// foreach (var ch in task.Title) _charSet.Add(ch);
// foreach (var ch in task.Description) _charSet.Add(ch);
// }
// #endif
//
// File.WriteAllText($"{outputFolderPath}{Path.DirectorySeparatorChar}charset.txt", string.Join("", _charSet));
// _charSet.Clear();
}
private void ExportAllGdbFiles()
{
string outputFolderPath = EditorUtility.SaveFolderPanel("选择GDB文件解包后的导出目录", "", "");
if (string.IsNullOrWhiteSpace(outputFolderPath))
return;
outputFolderPath += Path.DirectorySeparatorChar + GameConstants.AppName + Path.DirectorySeparatorChar;
if (!Directory.Exists(outputFolderPath))
{
Directory.CreateDirectory(outputFolderPath);
}
consoleTextUI.text = "正在解包GDB文件,请稍等...";
JsonConverter[] converters =
{
new StringEnumConverter(),
new ByteArrayConverter()
};
string combatActorInfos = JsonConvert.SerializeObject(_resourceProvider.GetCombatActorInfos(),
Formatting.Indented, converters);
File.WriteAllText(outputFolderPath + "CombatActors.json", combatActorInfos);
string combatSkillInfos = JsonConvert.SerializeObject(_resourceProvider.GetSkillInfos(),
Formatting.Indented, converters);
File.WriteAllText(outputFolderPath + "CombatSkills.json", combatSkillInfos);
string combatComboSkillInfos = JsonConvert.SerializeObject(_resourceProvider.GetComboSkillInfos(),
Formatting.Indented, converters);
File.WriteAllText(outputFolderPath + "CombatComboSkills.json", combatComboSkillInfos);
string gameItemInfos = JsonConvert.SerializeObject(_resourceProvider.GetGameItemInfos(),
Formatting.Indented, converters);
File.WriteAllText(outputFolderPath + "GameItems.json", gameItemInfos);
consoleTextUI.text = "GDB文件已解包完成!";
}
private void ExtractAllCpkArchives()
{
string outputFolderPath = EditorUtility.SaveFolderPanel("选择CPK解包后的导出目录", "", "");
if (string.IsNullOrWhiteSpace(outputFolderPath))
return;
outputFolderPath += Path.DirectorySeparatorChar + GameConstants.AppName + Path.DirectorySeparatorChar;
if (!Directory.Exists(outputFolderPath))
{
Directory.CreateDirectory(outputFolderPath);
}
extractAllCpkFilesButton.interactable = false;
consoleTextUI.text = "正在解包全部CPK文件,请稍等...";
StartCoroutine(ExtractAllCpkArchivesInternalAsync(outputFolderPath));
}
private bool _isMovieCpkMounted = false;
private IEnumerator ExtractAllCpkArchivesInternalAsync(string outputFolderPath)
{
// Movie CPKs are not mounted by default since we don't need them in normal gameplay.
// Mount them here if they are not mounted yet. So that we can extract them as well.
if (!_isMovieCpkMounted)
{
foreach (string movieCpkFileName in FileConstants.MovieCpkFileNames)
{
string movieCpkFilePath = FileConstants.GetMovieCpkFileRelativePath(movieCpkFileName);
if (File.Exists(_fileSystem.GetRootPath() + movieCpkFilePath))
{
_fileSystem.Mount(movieCpkFilePath, _codePage);
}
}
_isMovieCpkMounted = true;
}
Thread workerThread = new(() =>
{
_fileSystem.ExtractTo(outputFolderPath);
})
{
IsBackground = true,
Priority = System.Threading.ThreadPriority.Highest
};
workerThread.Start();
while (workerThread.IsAlive)
{
yield return null;
}
consoleTextUI.text = "全部CPK文件已解包完成!";
extractAllCpkFilesButton.interactable = true;
}
#endif
private readonly Dictionary<string, int> _actorDialogueCountMap = new();
private bool DecompileSce(string filePath, string outputFolderPath, bool dialogueOnly)
{
StringBuilder output = new();
SceFile sceFile;
try
{
IFileReader<SceFile> sceFileReader = new SceFileReader();
sceFile = sceFileReader.Read(_fileSystem.ReadAllBytes(filePath), _codePage);
}
catch (Exception ex)
{
EngineLogger.LogException(ex);
return true;
}
foreach (KeyValuePair<uint, SceScriptBlock> scriptBlock in sceFile.ScriptBlocks)
{
output.Append($"----------------------------------------------------------");
output.Append($"\n{scriptBlock.Value.Id} {scriptBlock.Value.Description}\n");
using SafeBinaryReader scriptDataReader = new(scriptBlock.Value.ScriptData);
int dialogueIndex = 1;
ICommand lastCommand = null;
while (scriptDataReader.BaseStream.Position < scriptDataReader.BaseStream.Length)
{
long currentPosition = scriptDataReader.BaseStream.Position;
ICommand command = _sceCommandParser.ParseNextCommand(scriptDataReader,
_codePage,
out _);
// if (command is DialogueRenderTextCommand dtc) foreach (var ch in dtc.DialogueText) _charSet.Add(ch);
// if (command is DialogueRenderTextWithTimeLimitCommand dttlc) foreach (var ch in dttlc.DialogueText) _charSet.Add(ch);
// if (command is UIDisplayNoteCommand unc) foreach (var ch in unc.Note) _charSet.Add(ch);
if (dialogueOnly && command is DialogueRenderTextCommand
or DialogueRenderTextWithTimeLimitCommand)
{
string dialogueText = command is DialogueRenderTextCommand textCommand
? textCommand.DialogueText
: ((DialogueRenderTextWithTimeLimitCommand)command).DialogueText;
bool isTimeLimited = command is DialogueRenderTextWithTimeLimitCommand;
string avatarTextureName = lastCommand is DialogueRenderActorAvatarCommand avatarCommand
? avatarCommand.AvatarTextureName
: string.Empty;
if (dialogueText.Contains("龙葵") && avatarTextureName.StartsWith("106"))
{
dialogueText = dialogueText.Replace("龙葵", "龙葵(红)");
}
dialogueText = dialogueText
.Replace("\\n", "")
.Replace("\\i", "")
.Replace("\\r", "");
output.Append(isTimeLimited
? $"{dialogueIndex:000} [限时对话] {dialogueText}\n"
: $"{dialogueIndex:000} {dialogueText}\n");
if (dialogueText.Contains(":"))
{
var actorName = dialogueText.Substring(0, dialogueText.IndexOf(":", StringComparison.Ordinal));
if (_actorDialogueCountMap.ContainsKey(actorName))
_actorDialogueCountMap[actorName]++;
else
_actorDialogueCountMap.Add(actorName, 1);
}
dialogueIndex++;
}
else if (!dialogueOnly)
{
output.Append($"{currentPosition} {command.GetType().Name.Replace("Command", "")} " +
$"{JsonConvert.SerializeObject(command)}\n");
}
lastCommand = command;
}
output.Append(dialogueOnly
? $"共{dialogueIndex - 1}句对话 \n"
: $"{scriptDataReader.BaseStream.Length} __END__\n");
}
string cpkFileName = filePath.Substring(filePath.LastIndexOf(CpkConstants.DirectorySeparatorChar) + 1).Replace(".sce", "");
string sceneName = SceneConstants.SceneCpkNameInfos
.FirstOrDefault(_ => string.Equals(_.cpkName, cpkFileName + CpkConstants.FileExtension, StringComparison.OrdinalIgnoreCase)).sceneName;
if (dialogueOnly && _actorDialogueCountMap.Count > 0)
{
output.AppendLine().AppendLine();
output.Append("-----角色对话统计----\n");
foreach (var actorDialogueCount in from entry
in _actorDialogueCountMap
orderby entry.Value descending
select entry)
{
output.Append($"{actorDialogueCount.Key} - {actorDialogueCount.Value}句\n");
}
}
File.WriteAllText(string.IsNullOrEmpty(sceneName)
? $"{outputFolderPath}{Path.DirectorySeparatorChar}{cpkFileName}.txt"
: $"{outputFolderPath}{Path.DirectorySeparatorChar}{cpkFileName}_{sceneName}.txt", output.ToString());
_actorDialogueCountMap.Clear();
return true;
}
private bool LoadMp3(string filePath)
{
nowPlayingTextUI.text = "* Now Playing: " + CoreUtility.GetFileName(filePath, CpkConstants.DirectorySeparatorChar);
StartCoroutine(LoadMp3AudioClipAsync(filePath,
_resourceProvider.GetMusicFilePathInCacheFolder(filePath)));
return true;
}
private IEnumerator LoadMp3AudioClipAsync(string fileVirtualPath, string writePath)
{
yield return _resourceProvider.ExtractAndMoveMp3FileToCacheFolderAsync(fileVirtualPath, writePath);
yield return _resourceProvider.LoadAudioClipAsync(writePath, AudioType.MPEG, streamAudio: true, audioClip =>
{
if (audioSource.isPlaying)
{
audioSource.Stop();
audioSource.clip.Destroy();
}
audioSource.clip = audioClip;
audioSource.volume = 0.5f;
audioSource.loop = true;
audioSource.Play();
});
}
private void DestroyExistingRenderingObjects()
{
if (_effectViewer != null)
_effectViewer.Stop();
foreach (Transform child in _renderingRoot.transform)
{
child.gameObject.Destroy();
}
// Unloads assets that are not used (textures etc.)
Resources.UnloadUnusedAssets();
}
}
internal sealed class ByteArrayConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(byte[]);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
byte[] bytes = (byte[])value;
writer.WriteStartArray();
if (bytes != null)
{
foreach (byte bt in bytes)
{
writer.WriteValue(bt);
}
}
writer.WriteEndArray();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
List<byte> bytes = new();
while (reader.Read())
{
if (reader.TokenType == JsonToken.Integer)
{
bytes.Add(Convert.ToByte(reader.Value));
}
else if (reader.TokenType == JsonToken.EndArray)
{
break;
}
}
return bytes.ToArray();
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: e9686113ddc1468493e51a5d319a46f4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,21 +0,0 @@
{
"name": "Pal3.ResourceViewer",
"rootNamespace": "",
"references": [
"GUID:7533bfa30c50146279c8ba7caae699e6",
"GUID:75cff0429b0fa4147a3d84da245baf0d",
"GUID:077e41948865f464a8105d046a0fdfe0",
"GUID:3de88c88fbbb8f944b9210d496af9762",
"GUID:6055be8ebefd69e48b49212b09b47b2f",
"GUID:75469ad4d38634e559750d17036d5f7c"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
+14
View File
@@ -72,6 +72,20 @@ namespace Pal3.Core.Tests
Assert.That(fs.FileExists("q02.cpk\\missing.bin"), Is.False);
}
[TestCase(false)]
[TestCase(true)]
public void MetadataReportsReadSizeWithoutReadingPayload(bool compressed)
{
string path = Fixture("q02_01.cpk", "data\\test.bin", compressed);
var fs = new CpkFileSystem(_root, Hash(), 936);
fs.Mount("q02_01.cpk", 936);
File.Delete(path);
var sizes = fs.GetFileSizes("Q02.CPK/DATA/TEST.BIN");
Assert.That(sizes.length, Is.EqualTo(5));
Assert.That(sizes.packedLength, Is.EqualTo(compressed ? 9 : 5));
Assert.Throws<FileNotFoundException>(() => fs.GetFileSizes("q02.cpk/missing"));
}
[Test]
public void TruncatedArchiveHeaderAndIndexTableAreRejected()
{
@@ -13,6 +13,7 @@ namespace Pal3.Game.Tests
using Constants;
using NUnit.Framework;
using UnityEditor;
using UnityEngine.Assemblies;
public sealed class ReleaseArchiveTests
{
@@ -26,7 +27,7 @@ namespace Pal3.Game.Tests
{
Directory.CreateDirectory(Path.GetDirectoryName(playerPath));
File.WriteAllBytes(playerPath, new byte[] { 1, 2, 3 });
Type pipeline = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetType("Editor.ReleaseBuildPipeline")).First(t => t != null);
Type pipeline = CurrentAssemblies.GetLoadedAssemblies().Select(a => a.GetType("Editor.ReleaseBuildPipeline")).First(t => t != null);
MethodInfo zip = pipeline.GetMethod("ZipReleaseFiles", BindingFlags.Static | BindingFlags.NonPublic, null, new[] { typeof(string) }, null);
zip.Invoke(null, new object[] { output });
string archive = Path.Combine(output, "Release", $"{GameConstants.AppName}_v{PlayerSettings.bundleVersion}_Windows_x64.zip");
@@ -1,6 +1,7 @@
fileFormatVersion: 2
guid: e65c4b938f18e6c4a86dc379157fac65
PrefabImporter:
guid: 11144f1e1b1f431c86bcc1bdfe2bbf87
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
@@ -1,6 +1,7 @@
fileFormatVersion: 2
guid: bfeeee050ceff400ea43322b909769dc
AssemblyDefinitionImporter:
guid: 2b2797c8d47842d08229f17336ffe699
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
@@ -0,0 +1,9 @@
{
"name": "Pal3.ResourceBrowser.Tests",
"references": ["Pal3.ResourceBrowser.Editor", "Pal3.Core", "Pal3.Game", "Engine"],
"includePlatforms": ["Editor"],
"optionalUnityReferences": ["TestAssemblies"],
"autoReferenced": false,
"overrideReferences": true,
"precompiledReferences": ["nunit.framework.dll"]
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 555ac7256da647788fa86e83aa82fa50
@@ -0,0 +1,229 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser.Tests
{
using System;
using System.IO;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using UnityEngine;
public sealed class ResourceCatalogTests
{
[TestCase("角色 ext:dds -missing", true)]
[TestCase("角色 ext:tga", false)]
[TestCase("-角色", false)]
[TestCase("BASEDATA.CPK/角色", true)]
public void QueryCombinesPathTypeAndExclusions(string query, bool expected)
{
Assert.That(ResourceCatalog.Matches(new ResourceEntry("basedata.cpk\\角色\\A.DDS"), query), Is.EqualTo(expected));
}
[TestCase("../escape.bin")]
[TestCase("archive.cpk/../../escape.bin")]
[TestCase("/absolute.bin")]
[TestCase("C:\\escape.bin")]
public void ExportRejectsUnsafePaths(string path)
{
Assert.Throws<InvalidDataException>(() => ResourceCatalog.ExportPath(Application.dataPath, path));
}
[Test]
public void ImageHeadersAreCheckedBeforeUnsafeTgaDecoding()
{
Assert.Throws<InvalidDataException>(() => ResourceImageData.Prepare(".tga", new byte[17]));
var tga = new byte[18];
tga[2] = 2;
tga[12] = 2;
tga[14] = 2;
tga[16] = 24;
Assert.Throws<InvalidDataException>(() => ResourceImageData.Prepare(".tga", tga));
tga[13] = 255;
Assert.Throws<InvalidDataException>(() => ResourceImageData.Prepare(".tga", tga));
}
[Test]
public void TgaImageIdAndTopOriginAreNormalizedWithoutChangingOriginalBytes()
{
var tga = new byte[25];
tga[0] = 1;
tga[2] = 2;
tga[12] = 1;
tga[14] = 2;
tga[16] = 24;
tga[17] = 32;
tga[19] = 10;
tga[22] = 20;
byte[] normalized = ResourceImageData.Prepare(".tga", tga);
Assert.That(normalized[18], Is.EqualTo(20));
Assert.That(normalized[21], Is.EqualTo(10));
Assert.That(tga[19], Is.EqualTo(10));
Assert.That(normalized.Length, Is.EqualTo(24));
}
[Test]
public void NativeTexturePreviewOwnsAndReleasesItsTexture()
{
var original = new Texture2D(2, 2);
original.SetPixels(new[] { Color.clear, Color.red, Color.green, Color.white });
original.Apply();
byte[] png = original.EncodeToPNG();
UnityEngine.Object.DestroyImmediate(original);
var preview = new ResourceTexturePreview(new ResourceEntry("image.png"), png);
Texture2D texture = preview.Texture;
Assert.That(texture.width, Is.EqualTo(2));
Assert.That(texture.GetPixel(0, 0).a, Is.Zero);
preview.Dispose();
Assert.That(texture == null, Is.True);
}
}
[TestFixture, Category("ResourceBrowserLocalData")]
public sealed class ResourceCatalogLocalTests
{
private ResourceCatalog _catalog;
private string _output;
[OneTimeSetUp]
public void Load()
{
string root = Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", ResourceBrowserWindow.Variant));
if (!Directory.Exists(root))
Assert.Ignore("Local game data is unavailable.");
_catalog = ResourceCatalog.Load(root, 936, ResourceBrowserWindow.Variant);
_output = Path.GetFullPath(Path.Combine(Application.dataPath, "../../workspace/ResourceBrowserQA/test-output", Guid.NewGuid().ToString("N")));
Directory.CreateDirectory(_output);
}
[OneTimeTearDown]
public void Cleanup()
{
_catalog?.Dispose();
if (_output != null && Directory.Exists(_output))
Directory.Delete(_output, true);
}
[Test]
public void CatalogIndexesRealDataAndExportsExactBytesWithoutOverwriting()
{
Assert.That(_catalog.Entries.Count, Is.GreaterThan(100000));
Assert.That(_catalog.Diagnostics, Is.Empty);
ResourceEntry entry = _catalog.Entries.First(e => e.Extension == ".dds");
var sizes = _catalog.GetSizes(entry);
byte[] expected = _catalog.Read(entry);
Assert.That(sizes.length, Is.EqualTo(expected.Length));
string output = ResourceCatalog.ExportPath(_output, entry.Path);
_catalog.ExportOriginal(entry, output);
Assert.That(File.ReadAllBytes(output), Is.EqualTo(expected));
Assert.Throws<IOException>(() => _catalog.ExportOriginal(entry, output));
Assert.Throws<IOException>(() => _catalog.CheckExportDestination(Path.Combine(_catalog.Root, "output")));
Assert.Throws<InvalidDataException>(() => _catalog.Read(entry, 1));
}
[Test]
public void MshJsonExportOmitsParentCyclesAndRetainsBoneRelationships()
{
ResourceEntry entry = _catalog.Entries.First(e => e.Extension == ".msh");
object model = ResourceFormats.Read(entry, _catalog.Read(entry), _catalog.Codepage);
string output = Path.Combine(_output, "skeleton.json");
ResourceBrowserWindow.WriteJson(model, output);
string json = File.ReadAllText(output);
Assert.That(json, Does.Contain("\"ParentId\""));
Assert.That(json, Does.Contain("\"Children\""));
}
[TestCase("obj/missing.dds")]
[TestCase("a/missing.dds")]
[TestCase("/missing.dds")]
[TestCase("missing.dds")]
[TestCase("missing.cpk/missing.dds")]
public void MissingLooseAndArchiveDependenciesReturnNull(string path)
{
Assert.That(_catalog.Find(path), Is.Null);
}
[Test]
public void FailedExportLeavesNoFinalOrPartialFile()
{
string destination = Path.Combine(_output, "failed.bin");
Assert.Throws<IOException>(() => ResourceCatalog.WriteNewFile(destination, stream =>
{
stream.WriteByte(1);
throw new IOException("Simulated write failure");
}));
Assert.That(File.Exists(destination), Is.False);
Assert.That(Directory.GetFiles(_output, "*.partial"), Is.Empty);
}
[Test]
public void SymbolicLinkInputCannotBypassOriginalDirectoryProtection()
{
if (Application.platform != RuntimePlatform.OSXEditor && Application.platform != RuntimePlatform.LinuxEditor)
Assert.Ignore("Symlink regression uses the Unix ln utility.");
string alias = Path.Combine(_output, "data-alias");
var start = new System.Diagnostics.ProcessStartInfo("/bin/ln") { UseShellExecute = false };
start.ArgumentList.Add("-s");
start.ArgumentList.Add(_catalog.Root);
start.ArgumentList.Add(alias);
using var process = System.Diagnostics.Process.Start(start);
process.WaitForExit();
Assert.That(process.ExitCode, Is.Zero);
try
{
var error = Assert.Throws<IOException>(() => ResourceCatalog.Load(alias, 936, ResourceBrowserWindow.Variant));
Assert.That(error.Message, Does.Contain("source data").And.Contain("real target"));
}
finally { Directory.Delete(alias); }
}
[Test]
public void IndexCancellationStopsWithoutReturningPartialCatalog()
{
using var cancellation = new CancellationTokenSource();
cancellation.Cancel();
Assert.Throws<OperationCanceledException>(() => ResourceCatalog.Load(_catalog.Root, 936, ResourceBrowserWindow.Variant, cancellation.Token));
}
[TestCase(".gdb")]
[TestCase(".sce")]
[TestCase(".csf")]
[TestCase(".par")]
[TestCase(".data")]
[TestCase(".scn")]
[TestCase(".nav")]
[TestCase(".lgt")]
public void RealSceneNavigationAndLightRecordsDecode(string extension)
{
ResourceEntry entry = _catalog.Entries.FirstOrDefault(e => e.Extension == extension &&
(extension != ".data" || e.Name.Equals("flexeff.data", StringComparison.OrdinalIgnoreCase)));
if (entry == null)
Assert.Ignore("No local sample for " + extension);
object decoded = ResourceFormats.Read(entry, _catalog.Read(entry), _catalog.Codepage);
Assert.That(decoded, Is.Not.Null);
if (decoded is Core.DataReader.Scn.ScnFile scene)
{
Assert.That(_catalog.Find(ResourceSceneData.BackgroundPath(scene.SceneInfo)), Is.Not.Null);
Assert.That(_catalog.Find(Core.Contract.Constants.FileConstants.GetNavFileVirtualPath(scene.SceneInfo.CityName, scene.SceneInfo.Model)), Is.Not.Null);
}
}
[TestCase(".dds")]
[TestCase(".tga")]
[TestCase(".bmp")]
public void RealTexturesCanBePreviewedAndExported(string extension)
{
ResourceEntry entry = _catalog.Entries.FirstOrDefault(e => e.Extension == extension);
if (entry == null)
Assert.Ignore("No sample for " + extension);
using var preview = new ResourceTexturePreview(entry, _catalog.Read(entry));
Assert.That(preview.Texture.width, Is.GreaterThan(0));
string output = Path.Combine(_output, "texture-" + extension[1..] + ".png");
preview.SavePng(output);
Assert.That(new FileInfo(output).Length, Is.GreaterThan(0));
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 11c8717a82c14ba58cf7435c55fd4851
@@ -0,0 +1,109 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser.Tests
{
using System;
using System.IO;
using System.Text;
using Core.DataReader.Sce;
using NUnit.Framework;
using UnityEngine;
public sealed class ResourceDataTests
{
[Test]
public void UnsupportedScriptBlockDoesNotHideLaterBlocksOrDialogue()
{
byte[] text = Encoding.GetEncoding(936).GetBytes("景天:测试");
using var stream = new MemoryStream();
using (var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true))
{
writer.Write((ushort)62);
writer.Write((ushort)0);
writer.Write((ushort)text.Length);
writer.Write(text);
}
var broken = new SceScriptBlock { Id = 1, Description = "broken", ScriptData = new byte[] { 255, 255, 0, 0 }, UserVariables = Array.Empty<SceUserVarInfo>() };
var valid = new SceScriptBlock { Id = 2, Description = "valid", ScriptData = stream.ToArray(), UserVariables = Array.Empty<SceUserVarInfo>() };
var file = new SceFile(Array.Empty<SceIndex>(), new[] { broken, valid }, 936);
var lines = ResourceScriptListing.Decode(valid, 936);
Assert.That(lines.Count, Is.EqualTo(1));
Assert.That(lines[0].Opcode, Is.EqualTo(62));
Assert.That(lines[0].VariableMask, Is.Zero);
Assert.That(lines[0].Dialogue, Is.EqualTo("景天:测试"));
using var output = new StringWriter();
ResourceScriptListing.Export(file, output, true);
Assert.That(output.ToString(), Does.Contain("ERROR in block 1"));
Assert.That(output.ToString(), Does.Contain("BLOCK 2"));
Assert.That(output.ToString(), Does.Contain("景天:测试"));
}
[TestCase(936, "仙剑三")]
[TestCase(950, "仙劍三")]
public void TextCopiesPreserveEncodingAndRejectUnrepresentableEdits(int codepage, string value)
{
var draft = ScriptableObject.CreateInstance<ResourceTextDraft>();
try
{
byte[] original = Encoding.GetEncoding(codepage).GetBytes(value);
draft.Load(original, codepage);
Assert.That(draft.Text, Is.EqualTo(value));
Assert.That(draft.Encode(false), Is.EqualTo(original));
draft.Text += "😀";
Assert.Throws<EncoderFallbackException>(() => draft.Encode(false));
Assert.That(Encoding.UTF8.GetString(draft.Encode(true)), Is.EqualTo(draft.Text));
}
finally { UnityEngine.Object.DestroyImmediate(draft); }
}
[Test]
public void TextBomAndUnsavedDraftSurviveSerialization()
{
var draft = ScriptableObject.CreateInstance<ResourceTextDraft>();
var restored = ScriptableObject.CreateInstance<ResourceTextDraft>();
try
{
byte[] data = new byte[] { 0xef, 0xbb, 0xbf, 65 };
draft.Load(data, 936);
Assert.That(draft.Codepage, Is.EqualTo(65001));
Assert.That(draft.Encode(false), Is.EqualTo(data));
draft.Text = "edited";
draft.SourcePath = "basedata.cpk\\config.ini";
JsonUtility.FromJsonOverwrite(JsonUtility.ToJson(draft), restored);
Assert.That(restored.Text, Is.EqualTo("edited"));
Assert.That(restored.SourcePath, Is.EqualTo(draft.SourcePath));
Assert.That(restored.IsDirty, Is.True);
}
finally
{
UnityEngine.Object.DestroyImmediate(draft);
UnityEngine.Object.DestroyImmediate(restored);
}
}
[Test]
public void ShortenedTextAndForeignCatalogDoNotReuseStaleContext()
{
Assert.That(ResourceTextDraft.ContextAt("short", 1000), Is.Empty);
var draft = ScriptableObject.CreateInstance<ResourceTextDraft>();
try
{
draft.SourceRoot = Path.GetFullPath("Game Data/PAL3");
Assert.That(draft.CanReadFrom(draft.SourceRoot), Is.True);
Assert.That(draft.CanReadFrom(Path.GetFullPath("Game Data/PAL3A")), Is.False);
}
finally { UnityEngine.Object.DestroyImmediate(draft); }
}
[Test]
public void UnknownDataExtensionsAreNotMisparsedAsEffects()
{
Assert.That(ResourceFormats.Read(new ResourceEntry("archive.cpk\\unknown.data"), new byte[4], 936), Is.Null);
Assert.That(ResourceFormats.Read(new ResourceEntry("archive.cpk\\unknown.dat"), new byte[4], 936), Is.Null);
Assert.That(ResourceFormats.Read(new ResourceEntry("archive.cpk\\unknown.par"), new byte[4], 936), Is.Null);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: fa42d0938d47483d9a894542ac46e00b
@@ -0,0 +1,241 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser.Tests
{
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.TestTools;
[TestFixture, Category("ResourceBrowserLocalData")]
public sealed class ResourceMediaTests
{
private ResourceCatalog _catalog;
[OneTimeSetUp]
public void Load()
{
string root = Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", ResourceBrowserWindow.Variant));
if (!Directory.Exists(root))
Assert.Ignore("Local game data is unavailable.");
_catalog = ResourceCatalog.Load(root, 936, ResourceBrowserWindow.Variant);
}
[OneTimeTearDown]
public void Cleanup() => _catalog?.Dispose();
[UnityTest]
public IEnumerator RealAudioLoadsAndReleasesArchiveTemporaryFiles()
{
foreach (string extension in new[] { ".wav", ".mp3" })
{
ResourceEntry entry = _catalog.Entries.First(e => e.Extension == extension);
using var preview = new ResourceMediaPreview(_catalog, entry);
double deadline = EditorApplication.timeSinceStartup + 35;
while (preview.Loading && EditorApplication.timeSinceStartup < deadline)
{
preview.Tick();
yield return null;
}
Assert.That(preview.Error, Is.Null, entry.Path);
Assert.That(preview.Ready, Is.True, entry.Path);
AudioClip clip = preview.Audio;
Assert.That(clip.length, Is.GreaterThan(0));
preview.Tick();
Assert.That(preview.Tick(), Is.False, "Idle audio must not continuously repaint the browser.");
string directory = preview.TemporaryDirectory;
ResourceMediaPreview.CleanupStaleTemporaryFiles();
if (directory != null)
Assert.That(Directory.Exists(directory), Is.True, "Cleanup must preserve active previews.");
preview.Dispose();
Assert.That(clip == null, Is.True);
if (directory != null)
Assert.That(Directory.Exists(directory), Is.False);
}
}
[UnityTest]
public IEnumerator RealVideoPlaysInPreviewSceneWithoutDirtyingCurrentScene()
{
Scene original = SceneManager.GetActiveScene();
bool dirty = original.isDirty;
ResourceEntry entry = _catalog.Entries.First(e => e.Extension == ".webm");
using var preview = new ResourceMediaPreview(_catalog, entry);
double deadline = EditorApplication.timeSinceStartup + 35;
while (preview.Loading && EditorApplication.timeSinceStartup < deadline)
{
preview.Tick();
yield return null;
}
Assert.That(preview.Error, Is.Null, entry.Path);
Assert.That(preview.Ready, Is.True);
var video = preview.Video;
video.Play();
Assert.That(preview.Tick(), Is.True, "Playing video must repaint.");
deadline = EditorApplication.timeSinceStartup + 10;
while (video.frame < 2 && EditorApplication.timeSinceStartup < deadline)
{
preview.Tick();
yield return null;
}
Assert.That(video.frame, Is.GreaterThanOrEqualTo(2));
Assert.That(video.texture, Is.Not.Null);
video.Pause();
foreach (double requestedTime in new[] { video.length * 0.5, 0, video.length })
{
bool seeked = false;
UnityEngine.Video.VideoPlayer.EventHandler handler = _ => seeked = true;
video.seekCompleted += handler;
double seekTime = Math.Min(requestedTime, video.length - 1 / video.frameRate);
preview.SeekVideo(requestedTime);
Assert.That(preview.Tick(), Is.True, "Seeking video must repaint.");
deadline = EditorApplication.timeSinceStartup + 10;
while ((!seeked || Math.Abs(video.frame / video.frameRate - seekTime) > 0.2) && EditorApplication.timeSinceStartup < deadline)
{
preview.Tick();
yield return null;
}
video.seekCompleted -= handler;
Assert.That(preview.Error, Is.Null);
Assert.That(seeked, Is.True, "Paused seek did not complete.");
Assert.That(video.frame / video.frameRate, Is.EqualTo(seekTime).Within(0.2), "Paused seek did not update the frame.");
Assert.That(video.isPlaying, Is.False);
preview.Tick();
Assert.That(preview.Tick(), Is.False, "Paused video must stop requesting repaints after the final frame.");
}
preview.SeekVideo(video.length * 0.25);
preview.SeekVideo(video.length * 0.5);
preview.SeekVideo(video.length * 0.75);
deadline = EditorApplication.timeSinceStartup + 10;
while (Math.Abs(video.frame / video.frameRate - video.length * 0.75) > 0.2 && EditorApplication.timeSinceStartup < deadline)
{
preview.Tick();
yield return null;
}
Assert.That(preview.Error, Is.Null);
Assert.That(video.frame / video.frameRate, Is.EqualTo(video.length * 0.75).Within(0.2), "Scrubbing must retain the latest requested time.");
Assert.That(video.isPlaying, Is.False);
preview.Tick();
Assert.That(preview.Tick(), Is.False);
double asynchronousSeek = video.length * 0.25;
preview.SeekVideo(asynchronousSeek);
deadline = EditorApplication.timeSinceStartup + 10;
while (Math.Abs(video.frame / video.frameRate - asynchronousSeek) > 0.2 && EditorApplication.timeSinceStartup < deadline)
{
// Let decoder callbacks finish between browser ticks.
EditorApplication.QueuePlayerLoopUpdate();
yield return null;
}
Assert.That(video.frame / video.frameRate, Is.EqualTo(asynchronousSeek).Within(0.2));
Assert.That(video.isPlaying, Is.False);
Assert.That(preview.Tick(), Is.True, "A completed asynchronous seek must repaint its final frame.");
Assert.That(preview.Tick(), Is.False);
typeof(ResourceMediaPreview).GetMethod("OnVideoError", BindingFlags.Instance | BindingFlags.NonPublic)
.Invoke(preview, new object[] { video, "Simulated decoder error" });
Assert.That(preview.Tick(), Is.True, "An error arriving while idle must repaint once.");
Assert.That(preview.Error, Is.EqualTo("Simulated decoder error"));
Assert.That(preview.Tick(), Is.False);
Assert.That(SceneManager.GetActiveScene(), Is.EqualTo(original));
Assert.That(original.isDirty, Is.EqualTo(dirty));
preview.Dispose();
Assert.That(video == null, Is.True);
}
[UnityTest]
public IEnumerator DisposingDuringExtractionCannotCreateMediaOrLeaveFiles()
{
ResourceEntry entry = _catalog.Entries.First(e => e.IsArchived && e.Extension == ".mp3");
var preview = new ResourceMediaPreview(_catalog, entry);
string directory = preview.TemporaryDirectory;
preview.Dispose();
double deadline = EditorApplication.timeSinceStartup + 2;
while (EditorApplication.timeSinceStartup < deadline)
{
preview.Tick();
yield return null;
}
Assert.That(preview.Audio, Is.Null);
Assert.That(preview.Video, Is.Null);
Assert.That(Directory.Exists(directory), Is.False);
}
[Test]
public void CleanupPreservesLiveAndUnrecognizedDirectories()
{
string root = Path.GetFullPath(Path.Combine(Application.dataPath, "../../workspace/ResourceBrowserMedia"));
using var process = Process.GetCurrentProcess();
string live = Path.Combine(root, process.Id + "-" + Guid.NewGuid().ToString("N"));
string stale = Path.Combine(root, int.MaxValue + "-" + Guid.NewGuid().ToString("N"));
string legacy = Path.Combine(root, Guid.NewGuid().ToString("N"));
string link = Path.Combine(root, int.MaxValue + "-" + Guid.NewGuid().ToString("N"));
string[] directories = { live, stale, legacy };
try
{
Assert.Throws<ArgumentException>(() => Process.GetProcessById(int.MaxValue));
foreach (string directory in directories)
{
Directory.CreateDirectory(directory);
File.WriteAllText(Path.Combine(directory, "preview.mp3"), "temporary media");
}
bool testLink = Application.platform is RuntimePlatform.OSXEditor or RuntimePlatform.LinuxEditor;
if (testLink)
{
var start = new ProcessStartInfo("/bin/ln") { UseShellExecute = false };
start.ArgumentList.Add("-s");
start.ArgumentList.Add(legacy);
start.ArgumentList.Add(link);
using var ln = Process.Start(start);
ln.WaitForExit();
Assert.That(ln.ExitCode, Is.Zero);
}
ResourceMediaPreview.CleanupStaleTemporaryFiles();
Assert.That(Directory.Exists(live), Is.True);
Assert.That(Directory.Exists(legacy), Is.True);
Assert.That(Directory.Exists(stale), Is.False);
Assert.That(File.ReadAllText(Path.Combine(legacy, "preview.mp3")), Is.EqualTo("temporary media"));
if (testLink)
Assert.That(Directory.Exists(link), Is.True, "Cleanup must not follow or remove symbolic links.");
}
finally
{
if (Directory.Exists(link))
Directory.Delete(link);
foreach (string directory in directories)
if (Directory.Exists(directory))
Directory.Delete(directory, true);
}
}
[Test]
public void BatchConversionsProduceDistinctScriptDialogueAndDatabaseFiles()
{
string output = Path.GetFullPath(Path.Combine(Application.dataPath, "../../workspace/ResourceBrowserQA/test-output", Guid.NewGuid().ToString("N")));
try
{
foreach (var mode in new[] { ResourceExportMode.Script, ResourceExportMode.Dialogue, ResourceExportMode.Json })
{
ResourceEntry entry = _catalog.Entries.First(e => e.Extension == (mode == ResourceExportMode.Json ? ".gdb" : ".sce"));
string destination = ResourceCatalog.ExportPath(output, entry.Path + ResourceExport.Suffix(mode));
ResourceExport.Write(_catalog, entry, mode, destination);
Assert.That(new FileInfo(destination).Length, Is.GreaterThan(0));
Assert.Throws<IOException>(() => ResourceExport.Write(_catalog, entry, mode, destination));
}
}
finally
{
if (Directory.Exists(output))
Directory.Delete(output, true);
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: db4afc3babfe4f2f88cfe3647dbebf91
@@ -0,0 +1,196 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser.Tests
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;
[TestFixture, Category("ResourceBrowserLocalData")]
public sealed class ResourceModelTests
{
private ResourceCatalog _catalog;
[OneTimeSetUp]
public void Load()
{
string root = Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", ResourceBrowserWindow.Variant));
if (!Directory.Exists(root))
Assert.Ignore("Local game data is unavailable.");
_catalog = ResourceCatalog.Load(root, 936, ResourceBrowserWindow.Variant);
}
[OneTimeTearDown]
public void Cleanup() => _catalog?.Dispose();
[Test]
public void Mv3SamplingBeforeFirstKeyAndBeyondClipHoldsFinitePoses()
{
ResourceEntry entry = _catalog.Entries.First(e => e.Extension == ".mv3");
var source = (Core.DataReader.Mv3.Mv3File)ResourceFormats.Read(entry, _catalog.Read(entry), _catalog.Codepage);
var meshes = source.Meshes.Select(mesh =>
{
mesh.KeyFrames = mesh.KeyFrames.Select(frame =>
{
frame.GameBoxTick += 4800;
return frame;
}).ToArray();
return mesh;
}).ToArray();
var shifted = new Core.DataReader.Mv3.Mv3File(source.TotalGameBoxTicks + 4800,
source.AnimationEvents, source.TagNodes, meshes, source.Materials);
using var preview = new ResourceModelPreview(_catalog, false);
preview.Load(entry, shifted);
preview.Sample(0);
preview.Sample(float.MaxValue);
Assert.That(preview.Root.GetComponentsInChildren<MeshFilter>().SelectMany(m => m.sharedMesh.vertices)
.All(v => float.IsFinite(v.x) && float.IsFinite(v.y) && float.IsFinite(v.z)), Is.True);
}
[TestCase("")]
[TestCase("obj")]
public void LooseModelsResolveTexturesAtRootAndInShortDirectories(string directory)
{
string output = Path.GetFullPath(Path.Combine(Application.dataPath, "../../workspace/ResourceBrowserQA/test-output", Guid.NewGuid().ToString("N")));
Directory.CreateDirectory(output);
try
{
const BindingFlags privateInstance = BindingFlags.Instance | BindingFlags.NonPublic;
using var catalog = (ResourceCatalog)Activator.CreateInstance(typeof(ResourceCatalog), privateInstance, null, new object[] { output, 936 }, null);
string texturePath = directory.Length == 0 ? "texture.tga" : directory + "\\texture.tga";
string filePath = Path.Combine(output, directory, "texture.tga");
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
var tga = new byte[21];
tga[2] = 2;
tga[12] = tga[14] = 1;
tga[16] = 24;
tga[20] = 255;
File.WriteAllBytes(filePath, tga);
var lookup = (Dictionary<string, ResourceEntry>)typeof(ResourceCatalog).GetField("_lookup", privateInstance).GetValue(catalog);
lookup.Add(texturePath, new ResourceEntry(texturePath, filePath));
ResourceEntry sourceEntry = _catalog.Entries.First(e => e.Extension == ".mv3");
var source = (Core.DataReader.Mv3.Mv3File)ResourceFormats.Read(sourceEntry, _catalog.Read(sourceEntry), _catalog.Codepage);
var materials = source.Materials.Select(material =>
{
material.TextureFileNames = new[] { "texture.tga" };
return material;
}).ToArray();
var model = new Core.DataReader.Mv3.Mv3File(source.TotalGameBoxTicks, source.AnimationEvents, source.TagNodes, source.Meshes, materials);
string modelPath = directory.Length == 0 ? "model.mv3" : directory + "\\model.mv3";
using var preview = new ResourceModelPreview(catalog, false);
preview.Load(new ResourceEntry(modelPath, Path.Combine(output, directory, "model.mv3")), model);
Assert.That(preview.Dependencies.Count, Is.EqualTo(1));
Assert.That(preview.Dependencies[texturePath], Is.True);
Assert.That(preview.Root.GetComponentsInChildren<MeshFilter>(), Is.Not.Empty);
}
finally { Directory.Delete(output, true); }
}
[Test]
public void PlayingFromTheEndRestartsAndPauseResumeKeepsTheCurrentTime()
{
const BindingFlags privateInstance = BindingFlags.Instance | BindingFlags.NonPublic;
ResourceEntry entry = _catalog.Entries.First(e => e.Extension == ".mv3");
using var preview = new ResourceModelPreview(_catalog, false);
preview.Load(entry, ResourceFormats.Read(entry, _catalog.Read(entry), _catalog.Codepage));
Assert.That(preview.Duration, Is.GreaterThan(0));
var window = ScriptableObject.CreateInstance<ResourceBrowserWindow>();
Type type = typeof(ResourceBrowserWindow);
try
{
type.GetMethod("CancelScan", privateInstance).Invoke(window, null);
type.GetField("_model", privateInstance).SetValue(window, preview);
type.GetField("_loop", privateInstance).SetValue(window, false);
FieldInfo time = type.GetField("_time", privateInstance);
FieldInfo playing = type.GetField("_playing", privateInstance);
MethodInfo toggle = type.GetMethod("ToggleModelPlayback", privateInstance);
time.SetValue(window, preview.Duration);
toggle.Invoke(window, null);
Assert.That(time.GetValue(window), Is.EqualTo(0f));
Assert.That(playing.GetValue(window), Is.True);
type.GetField("_lastTick", privateInstance).SetValue(window, EditorApplication.timeSinceStartup - 0.05);
type.GetMethod("TickModel", privateInstance).Invoke(window, null);
float resumedTime = (float)time.GetValue(window);
Assert.That(resumedTime, Is.GreaterThan(0).And.LessThan(preview.Duration));
Assert.That(playing.GetValue(window), Is.True);
toggle.Invoke(window, null);
Assert.That(playing.GetValue(window), Is.False);
toggle.Invoke(window, null);
Assert.That(time.GetValue(window), Is.EqualTo(resumedTime));
}
finally
{
type.GetField("_model", privateInstance).SetValue(window, null);
UnityEngine.Object.DestroyImmediate(window);
}
}
[TestCase(".pol", false)]
[TestCase(".pol", true)]
[TestCase(".cvd", false)]
[TestCase(".cvd", true)]
[TestCase(".mv3", false)]
[TestCase(".mv3", true)]
[TestCase(".msh", false)]
[TestCase(".msh", true)]
[TestCase(".mov", false)]
[TestCase(".mov", true)]
public void RealModelsRenderSampleDeterministicallyAndReleaseOwnedResources(string extension, bool toon)
{
ResourceEntry entry = _catalog.Entries.FirstOrDefault(e => e.Extension == extension);
if (entry == null)
Assert.Ignore("No local sample for " + extension);
object decoded = ResourceFormats.Read(entry, _catalog.Read(entry), _catalog.Codepage);
Scene active = SceneManager.GetActiveScene();
bool wasDirty = active.isDirty;
using var preview = new ResourceModelPreview(_catalog, toon);
preview.Load(entry, decoded);
GameObject root = preview.Root;
Assert.That(EditorSceneManager.IsPreviewScene(root.scene), Is.True);
Assert.That(SceneManager.GetActiveScene(), Is.EqualTo(active));
Mesh[] meshes = root.GetComponentsInChildren<MeshFilter>().Select(f => f.sharedMesh).ToArray();
Assert.That(meshes.Length, Is.GreaterThan(0));
Material[] materials = root.GetComponentsInChildren<Renderer>().SelectMany(r => r.sharedMaterials).ToArray();
preview.Sample(preview.Duration * 0.5f);
Vector3[][] middle = meshes.Select(m => m.vertices).ToArray();
preview.Sample(0);
preview.Sample(preview.Duration);
preview.Sample(preview.Duration * 0.5f);
for (int i = 0; i < meshes.Length; i++)
Assert.That(meshes[i].vertices, Is.EqualTo(middle[i]), entry.Path);
Assert.That(meshes.SelectMany(m => m.vertices).All(v => float.IsFinite(v.x) && float.IsFinite(v.y) && float.IsFinite(v.z)), Is.True);
RenderTexture target = preview.Render(256, 256);
var image = new Texture2D(256, 256, TextureFormat.RGBA32, false);
RenderTexture previous = RenderTexture.active;
try
{
RenderTexture.active = target;
image.ReadPixels(new Rect(0, 0, 256, 256), 0, 0);
image.Apply();
Assert.That(image.GetPixels32().Distinct().Count(), Is.GreaterThan(4), "Preview is blank: " + entry.Path);
}
finally
{
RenderTexture.active = previous;
Object.DestroyImmediate(image);
}
preview.Dispose();
Assert.That(root == null, Is.True);
Assert.That(meshes.All(m => m == null), Is.True);
Assert.That(materials.All(m => m == null), Is.True);
Assert.That(active.isDirty, Is.EqualTo(wasDirty));
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8b2d84fcb3e74594ae4958843dff7fb0
@@ -0,0 +1,51 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser.Tests
{
using Core.Contract.Enums;
using Core.DataReader.Nav;
using Core.DataReader.Scn;
using Core.Primitives;
using NUnit.Framework;
using UnityEngine;
public sealed class ResourceSceneTests
{
[Test]
public void ScenePathsMatchRuntimeNightAndObjectRules()
{
var scene = new ScnSceneInfo { CityName = "q02", Model = "3", LightMap = 1 };
Assert.That(ResourceSceneData.BackgroundPath(scene), Is.EqualTo("q02.cpk\\3\\1\\3.pol"));
Assert.That(ResourceSceneData.ObjectPath(scene, new ScnObjectInfo { Name = "_a.pol" }), Is.EqualTo("q02.cpk\\3\\_a.pol"));
Assert.That(ResourceSceneData.ObjectPath(scene, new ScnObjectInfo { Name = "+effect" }), Is.Null);
}
[Test]
public void NavPickingUsesBottomLeftOriginAndPreservesBlockedTileMeaning()
{
var layer = new NavLayer { Width = 4, Height = 2 };
var rect = new Rect(10, 20, 40, 20);
Assert.That(ResourceSceneData.TileAt(new Vector2(15, 25), rect, layer), Is.EqualTo(new Vector2Int(0, 1)));
Assert.That(ResourceSceneData.TileAt(new Vector2(45, 35), rect, layer), Is.EqualTo(new Vector2Int(3, 0)));
var obstacle = new NavTile { IsObstacle = true };
var nearObstacle = new NavTile { IsObstacle = false, DistanceToNearestObstacle = 0 };
var walkable = new NavTile { IsObstacle = false, DistanceToNearestObstacle = 1 };
Assert.That(ResourceSceneData.TileColor(nearObstacle), Is.Not.EqualTo(ResourceSceneData.TileColor(obstacle)));
Assert.That(ResourceSceneData.TileColor(nearObstacle), Is.Not.EqualTo(ResourceSceneData.TileColor(walkable)));
}
[Test]
public void NpcMarkersUseNavigationHeightUnlessHolding()
{
var npc = new ScnNpcInfo { GameBoxXPosition = 6, GameBoxZPosition = 6, GameBoxYPosition = 100, LayerIndex = 0 };
var layer = new NavLayer { Width = 1, Height = 1, GameBoxMinWorldPosition = new GameBoxVector3(0, 0, 0), Tiles = new[] { new NavTile { GameBoxYPosition = 40 } } };
var nav = new NavFile(new[] { layer }, System.Array.Empty<NavMeshData>());
Assert.That(ResourceSceneData.NpcPosition(npc, nav), Is.EqualTo(new Vector3(-0.3f, 2, 0.3f)));
npc.InitBehaviour = ActorBehaviourType.Hold;
Assert.That(ResourceSceneData.NpcPosition(npc, nav).y, Is.EqualTo(5));
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a91f34c83af54cb0b61ece9aa871d796
@@ -0,0 +1,271 @@
// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.ResourceBrowser.Tests
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
using UnityEngine.TestTools;
using Object = UnityEngine.Object;
public sealed class ResourceWindowLifecycleTests
{
private const string WindowName = "ResourceBrowserReloadTest";
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
private sealed class KeyboardFocusProbe : EditorWindow
{
public ResourceBrowserWindow Browser;
public bool FocusList, InputFocused, ListFocused;
public bool DrawList, ExitedGui, ScrollClosedAtExit, ListFocusedAtExit;
public Vector2 MousePosition;
private string _text = "Input";
private void OnGUI()
{
if (Event.current.type == EventType.MouseMove)
MousePosition = Event.current.mousePosition;
int listControl = GUIUtility.GetControlID(FocusType.Keyboard);
if (FocusList)
{
GUIUtility.keyboardControl = listControl;
FocusList = false;
}
Vector2 origin = GUIUtility.GUIToScreenPoint(Vector2.zero);
try
{
typeof(ResourceBrowserWindow).GetMethod("HandleListKeys", Private).Invoke(Browser, new object[] { listControl });
if (DrawList)
typeof(ResourceBrowserWindow).GetMethod("DrawList", Private).Invoke(Browser, new object[] { new Rect(0, 60, 240, 180), listControl });
}
catch (TargetInvocationException ex) when (ex.InnerException is ExitGUIException)
{
ExitedGui = true;
ScrollClosedAtExit = GUIUtility.GUIToScreenPoint(Vector2.zero) == origin;
ListFocusedAtExit = GUIUtility.keyboardControl == listControl;
throw ex.InnerException;
}
GUI.SetNextControlName("TestInput");
_text = EditorGUILayout.TextField(_text);
InputFocused = GUI.GetNameOfFocusedControl() == "TestInput";
ListFocused = GUIUtility.keyboardControl == listControl;
}
}
[UnityTest]
public IEnumerator MouseAndKeyboardSelectionExitTheCurrentGuiPass()
{
string output = Path.GetFullPath(Path.Combine(Application.dataPath, "../../workspace/ResourceBrowserQA/test-output", Guid.NewGuid().ToString("N")));
Directory.CreateDirectory(output);
var window = ScriptableObject.CreateInstance<ResourceBrowserWindow>();
var probe = ScriptableObject.CreateInstance<KeyboardFocusProbe>();
try
{
typeof(ResourceBrowserWindow).GetMethod("CancelScan", Private).Invoke(window, null);
var catalog = (ResourceCatalog)Activator.CreateInstance(typeof(ResourceCatalog), Private, null, new object[] { output, 936 }, null);
typeof(ResourceBrowserWindow).GetField("_catalog", Private).SetValue(window, catalog);
var entries = (List<ResourceEntry>)typeof(ResourceBrowserWindow).GetField("_visible", Private).GetValue(window);
var binary = new ResourceEntry("first.bin", Path.Combine(output, "first.bin"));
var text = new ResourceEntry("second.txt", Path.Combine(output, "second.txt"));
File.WriteAllBytes(binary.PhysicalPath, new byte[] { 1, 2, 3 });
File.WriteAllText(text.PhysicalPath, "Selected text");
entries.Add(binary);
entries.Add(text);
probe.Browser = window;
probe.DrawList = true;
probe.wantsMouseMove = true;
probe.Show();
probe.Focus();
yield return null;
foreach (bool mouse in new[] { true, false })
{
typeof(ResourceBrowserWindow).GetMethod("Select", Private).Invoke(window, new object[] { binary });
probe.FocusList = true;
probe.SendEvent(new Event { type = EventType.Repaint });
probe.ExitedGui = false;
var click = new Vector2(20, 108);
probe.SendEvent(new Event { type = EventType.MouseMove, mousePosition = click });
// SendEvent uses host-view coordinates; account for the window's tab offset.
click += click - probe.MousePosition;
probe.SendEvent(mouse
? new Event { type = EventType.MouseDown, button = 0, mousePosition = click }
: new Event { type = EventType.KeyDown, keyCode = KeyCode.DownArrow });
Assert.That(probe.ExitedGui, Is.True, mouse ? "Mouse selection" : "Keyboard selection");
Assert.That(probe.ScrollClosedAtExit, Is.True, "The scroll view must close before selection exits OnGUI.");
Assert.That(probe.ListFocusedAtExit, Is.True, "Selection must preserve list keyboard focus.");
Assert.That(typeof(ResourceBrowserWindow).GetField("_selected", Private).GetValue(window), Is.SameAs(text), mouse ? "Mouse selection" : "Keyboard selection");
var draft = (ResourceTextDraft)typeof(ResourceBrowserWindow).GetField("_textDraft", Private).GetValue(window);
Assert.That(draft.Text, Is.EqualTo("Selected text"));
probe.SendEvent(new Event { type = EventType.Repaint });
}
}
finally
{
probe.Close();
window.DiscardChanges();
Object.DestroyImmediate(window);
Directory.Delete(output, true);
}
}
[UnityTest]
public IEnumerator ListNavigationDoesNotConsumeArrowsAfterKeyboardFocusMovesToAnInput()
{
var window = ScriptableObject.CreateInstance<ResourceBrowserWindow>();
var probe = ScriptableObject.CreateInstance<KeyboardFocusProbe>();
try
{
typeof(ResourceBrowserWindow).GetMethod("CancelScan", Private).Invoke(window, null);
var entries = (List<ResourceEntry>)typeof(ResourceBrowserWindow).GetField("_visible", Private).GetValue(window);
entries.Add(new ResourceEntry("first.txt"));
entries.Add(new ResourceEntry("second.txt"));
FieldInfo selection = typeof(ResourceBrowserWindow).GetField("_selected", Private);
selection.SetValue(window, entries[0]);
probe.Browser = window;
probe.Show();
probe.Focus();
yield return null;
probe.FocusList = true;
probe.SendEvent(new Event { type = EventType.Repaint });
Assert.That(probe.ListFocused, Is.True);
probe.SendEvent(new Event { type = EventType.KeyDown, keyCode = KeyCode.Tab, character = '\t' });
probe.SendEvent(new Event { type = EventType.Repaint });
Assert.That(probe.InputFocused, Is.True, "Tab must transfer the list's keyboard focus to the input.");
probe.SendEvent(new Event { type = EventType.KeyDown, keyCode = KeyCode.DownArrow });
Assert.That(selection.GetValue(window), Is.SameAs(entries[0]));
}
finally
{
probe.Close();
Object.DestroyImmediate(window);
}
}
[TestCase(true, true)]
[TestCase(false, true)]
[TestCase(true, false)]
public void CompletedIndexRebindsDraftSelectionOnlyToItsOriginalCatalog(bool sameRoot, bool sourceExists)
{
string output = Path.GetFullPath(Path.Combine(Application.dataPath, "../../workspace/ResourceBrowserQA/test-output", Guid.NewGuid().ToString("N")));
Directory.CreateDirectory(output);
string pathPreference = ResourceBrowserWindow.Variant + ".ResourceBrowser.Path";
string codepagePreference = ResourceBrowserWindow.Variant + ".ResourceBrowser.Codepage";
bool hadPath = EditorPrefs.HasKey(pathPreference), hadCodepage = EditorPrefs.HasKey(codepagePreference);
string previousPath = EditorPrefs.GetString(pathPreference);
int previousCodepage = EditorPrefs.GetInt(codepagePreference);
var window = ScriptableObject.CreateInstance<ResourceBrowserWindow>();
try
{
typeof(ResourceBrowserWindow).GetMethod("CancelScan", Private).Invoke(window, null);
using var catalog = (ResourceCatalog)Activator.CreateInstance(typeof(ResourceCatalog), Private, null, new object[] { output, 936 }, null);
var entry = new ResourceEntry("draft.txt", Path.Combine(output, "draft.txt"));
catalog.Entries.Add(new ResourceEntry("before.txt"));
if (sourceExists)
{
catalog.Entries.Add(entry);
var lookup = (Dictionary<string, ResourceEntry>)typeof(ResourceCatalog).GetField("_lookup", Private).GetValue(catalog);
lookup.Add(entry.Path, entry);
}
catalog.Entries.Add(new ResourceEntry("later.txt"));
var draft = ScriptableObject.CreateInstance<ResourceTextDraft>();
draft.hideFlags = HideFlags.HideInHierarchy | HideFlags.DontSave;
draft.SourceRoot = sameRoot ? output : Path.Combine(output, "other");
draft.SourcePath = entry.Path;
draft.PhysicalPath = Path.Combine(draft.SourceRoot, "draft.txt");
draft.Load(System.Text.Encoding.UTF8.GetBytes("original"), 65001);
draft.Text = "unsaved text after reload";
typeof(ResourceBrowserWindow).GetField("_textDraft", Private).SetValue(window, draft);
typeof(ResourceBrowserWindow).GetMethod("RestoreTextDraft", Private).Invoke(window, null);
FieldInfo selection = typeof(ResourceBrowserWindow).GetField("_selected", Private);
Assert.That(selection.GetValue(window), Is.Not.SameAs(entry));
typeof(ResourceBrowserWindow).GetField("_scan", Private).SetValue(window, Task.FromResult(catalog));
typeof(ResourceBrowserWindow).GetMethod("Tick", Private).Invoke(window, null);
var selected = (ResourceEntry)selection.GetValue(window);
var visible = (List<ResourceEntry>)typeof(ResourceBrowserWindow).GetField("_visible", Private).GetValue(window);
Assert.That(selected.Path, Is.EqualTo(draft.SourcePath));
Assert.That(selected.PhysicalPath, Is.EqualTo(draft.PhysicalPath));
Assert.That(visible.IndexOf(selected), Is.EqualTo(sameRoot && sourceExists ? 1 : -1));
if (sameRoot && sourceExists)
Assert.That(selected, Is.SameAs(entry), "Highlight and arrow navigation must use the newly indexed entry.");
else
Assert.That(selected, Is.Not.SameAs(entry), "A foreign or missing source must keep a detached draft.");
Assert.That(draft.Text, Is.EqualTo("unsaved text after reload"));
Assert.That(window.hasUnsavedChanges, Is.True);
}
finally
{
window.DiscardChanges();
Object.DestroyImmediate(window);
if (hadPath)
EditorPrefs.SetString(pathPreference, previousPath);
else
EditorPrefs.DeleteKey(pathPreference);
if (hadCodepage)
EditorPrefs.SetInt(codepagePreference, previousCodepage);
else
EditorPrefs.DeleteKey(codepagePreference);
Directory.Delete(output, true);
}
}
[UnityTest]
public IEnumerator UnsavedTextSurvivesRealAssemblyReloadAndClosesCleanlyAfterDiscard()
{
if (!SessionState.GetBool(WindowName, false))
{
var window = ScriptableObject.CreateInstance<ResourceBrowserWindow>();
window.name = WindowName;
window.Show();
var draft = ScriptableObject.CreateInstance<ResourceTextDraft>();
draft.hideFlags = HideFlags.HideInHierarchy | HideFlags.DontSave;
draft.SourceRoot = System.IO.Path.GetFullPath(System.IO.Path.Combine(Application.dataPath, "../../Game Data", ResourceBrowserWindow.Variant));
draft.SourcePath = "reload-test.txt";
draft.Load(System.Text.Encoding.UTF8.GetBytes("original"), 65001);
draft.Text = "unsaved text after reload";
using var serialized = new SerializedObject(window);
serialized.FindProperty("_textDraft").objectReferenceValue = draft;
serialized.ApplyModifiedPropertiesWithoutUndo();
typeof(ResourceBrowserWindow).GetMethod("UpdateTextDirty", Private).Invoke(window, null);
SessionState.SetBool(WindowName, true);
EditorUtility.RequestScriptReload();
}
yield return new WaitForDomainReload();
ResourceBrowserWindow restored = Resources.FindObjectsOfTypeAll<ResourceBrowserWindow>().Single(w => w.name == WindowName);
try
{
using var serialized = new SerializedObject(restored);
var draft = (ResourceTextDraft)serialized.FindProperty("_textDraft").objectReferenceValue;
Assert.That(draft, Is.Not.Null);
Assert.That(draft.Text, Is.EqualTo("unsaved text after reload"));
Assert.That(draft.IsDirty, Is.True);
Assert.That(restored.hasUnsavedChanges, Is.True);
var selected = (ResourceEntry)typeof(ResourceBrowserWindow).GetField("_selected", Private).GetValue(restored);
Assert.That(selected.Path, Is.EqualTo(draft.SourcePath));
restored.DiscardChanges();
Assert.That(restored.hasUnsavedChanges, Is.False);
restored.Close();
Assert.That(draft == null, Is.True);
}
finally
{
SessionState.EraseBool(WindowName);
if (restored != null)
{
restored.DiscardChanges();
restored.Close();
}
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c0ef2bd0ad454982ab6596c25f8e9dd5
@@ -5,9 +5,6 @@ EditorBuildSettings:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Scenes:
- enabled: 0
path: Assets/Scenes/ResourceViewer.unity
guid: 9fc0d4010bbf28b4594072e72b8655ab
- enabled: 1
path: Assets/Scenes/Game.unity
guid: 72b9fc20ba5844018b72e08c9cf4ec97
+23 -6
View File
@@ -35,24 +35,41 @@ This is an open-source project that re-implements [The Legend of Sword and Fairy
Note: The Legend of Sword and Fairy 3 and The Legend of Sword and Fairy 3 Gaiden: Wenqing Pian are original works of Softstar Technology (Shanghai) Co., Ltd., with copyrights belonging to Softstar Technology (Shanghai) Co., Ltd. and Softstar International Inc. (I might be wrong but please verify yourself). This project does not contain any game data from the original game. The project is under the GPL-3.0 license but is limited to the code of this project excluding Unity assets and other assets and plugins that I used and get from Unity Asset Store. Any textures, audio, video, or game data related to The Legend of Sword and Fairy 3 or The Legend of Sword and Fairy 3 Gaiden: Wenqing Pian are not covered by this license.
## Build status
## Latest PR build status
CI runs only on pull requests. Each badge shows the latest pull request build for that workflow; click it to view the corresponding PR build history.
| Game Variant | Windows | Linux | MacOS | Android | iOS |
|-------------------------|---------|-------|-------|---------|-----|
| The Legend of Sword and Fairy 3 | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3-mono-windows.yml"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3-mono-windows.yml" alt="Size" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3-mono-linux.yml"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3-mono-linux.yml" alt="Size" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3-mono-macos.yml"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3-mono-macos.yml" alt="Size" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3-mono-android.yml"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3-mono-android.yml" alt="Size" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3-mono-ios.yml"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3-mono-ios.yml" alt="Size" /></a> |
| The Legend of Sword and Fairy 3 Gaiden: Wenqing Pian | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3a-mono-windows.yml"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3a-mono-windows.yml" alt="Size" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3a-mono-linux.yml"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3a-mono-linux.yml" alt="Size" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3a-mono-macos.yml"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3a-mono-macos.yml" alt="Size" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3a-mono-android.yml"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3a-mono-android.yml" alt="Size" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3a-mono-ios.yml"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3a-mono-ios.yml" alt="Size" /></a> |
| The Legend of Sword and Fairy 3 | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3-mono-windows.yml?query=event%3Apull_request"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3-mono-windows.yml?event=pull_request" alt="PR build status" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3-mono-linux.yml?query=event%3Apull_request"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3-mono-linux.yml?event=pull_request" alt="PR build status" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3-mono-macos.yml?query=event%3Apull_request"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3-mono-macos.yml?event=pull_request" alt="PR build status" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3-mono-android.yml?query=event%3Apull_request"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3-mono-android.yml?event=pull_request" alt="PR build status" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3-mono-ios.yml?query=event%3Apull_request"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3-mono-ios.yml?event=pull_request" alt="PR build status" /></a> |
| The Legend of Sword and Fairy 3 Gaiden: Wenqing Pian | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3a-mono-windows.yml?query=event%3Apull_request"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3a-mono-windows.yml?event=pull_request" alt="PR build status" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3a-mono-linux.yml?query=event%3Apull_request"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3a-mono-linux.yml?event=pull_request" alt="PR build status" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3a-mono-macos.yml?query=event%3Apull_request"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3a-mono-macos.yml?event=pull_request" alt="PR build status" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3a-mono-android.yml?query=event%3Apull_request"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3a-mono-android.yml?event=pull_request" alt="PR build status" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3a-mono-ios.yml?query=event%3Apull_request"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3a-mono-ios.yml?event=pull_request" alt="PR build status" /></a> |
## How to run the project
Open the project with the Unity version specified in [ProjectVersion.txt](ProjectSettings/ProjectVersion.txt). The project uses URP Forward+.
- Since the project itself does not contain any game data from the original game, you will need a copy of the original game files for The Legend of Sword and Fairy 3 or The Legend of Sword and Fairy 3 Gaiden: Wenqing Pian (Link to the game on Steam: [The Legend of Sword and Fairy 3](https://store.steampowered.com/app/1536070) and [The Legend of Sword and Fairy 3 Gaiden: Wenqing Pian](https://store.steampowered.com/app/1536080)).
- After opening the Unity project for the first time, double-click to select "Scenes\Game" as the current scene, and then press the play button. If you select "Scenes\ResourceViewer", it will open the game resource viewer.
- Open `Scenes/Game` and press Play to run the game. Use `PAL3 / PAL3A → Resource Browser` to browse resources in Edit Mode.
- The first time you open it, a folder selection window will automatically pop up. Please select the installation folder for The Legend of Sword and Fairy 3 (or The Legend of Sword and Fairy 3 Gaiden: Wenqing Pian) on your computer.
- Since the original game's cutscene videos are in Bink format, which Unity does not natively support, please convert the videos to a format supported by Unity and place them in the movie folder at the game's root directory (most devices and platforms support mainstream formats like .mp4, while Linux only supports .webm format).
- Linux users can use FFmpeg to convert videos to .webm format
```
ffmpeg -i input.mp4 -c:v libvpx -b:v 3M -c:a libvorbis output.webm // vp8 + vorbis
```
Note: You need to first decompress the OG game data to get the .bik videos. You can do this by clicking the "Extract all .cpk files" button under "Scenes\ResourceViewer" scene, which decompress all the CPK archives in the OG game data folder to a destination folder you choose. All .bik videos will be extracted to the output location once completed.
To extract the original videos, open `Resource Browser`, index the original installation directory, search `ext:bik`, and choose `Original → Export filtered…`. Archive entries larger than 64 MiB require individual confirmation with `Export original…`. The archive directory structure is preserved.
## Editor resource browser
Open the dockable window through `PAL3 / PAL3A → Resource Browser`. Choose the data directory containing `basedata/`, select GBK (936) or Big5 (950), and click `Index / Reload`. Use `Switch Variant` to change games.
The data directory and its ancestors must not be symbolic links; select the link's real target path instead. Indexing also skips links inside the directory. This restriction keeps path aliases from bypassing original-data export protection.
- Search paths with multiple terms, `-exclusions`, or `ext:dds`; filter by category/archive and navigate results with arrow keys.
- Textures use Unity's native preview and channel controls, with PNG export. Models offer an isolated viewport, original/Toon rendering, animation playback and seeking, and texture dependency links.
- SCN provides scene/NPC/object records, dependency links, and a static background with position markers. NAV provides layered walkability maps and tile details; LGT exposes light records.
- SCE shows script blocks, commands, variables and dialogue. GDB provides searchable item, actor, skill and combo tables. Parsed resources support field inspection and JSON export; scripts support batch listings and dialogue export.
- Text supports encoding detection, search, Undo and saving a copy. Audio uses native preview controls. Video uses Unity's platform decoder; BIK is extraction only. Unknown resources have a paged hex view.
Original data is read-only. Exports preserve hierarchy and never overwrite existing files. Choose `Original / Script / Dialogue / Json` before exporting filtered results; batch export is cancellable. Ordinary previews are limited to 64 MiB, text reads to 4 MiB, and in-window editing to 60,000 characters. Temporary media is extracted under `workspace/ResourceBrowserMedia/` beside the project and cleaned up when switching resources or closing the window. Opening the window also removes temporary directories left by exited processes. Effect playback and override editing remain in `Effect Editor`. The old `ResourceViewer` scene has been removed.
## How to run the game
- In runtime, when the game is launched for the first time, it will search the [Application.persistentDataPath](https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Application-persistentDataPath.html) directory or the [StreamingAssets](https://docs.unity3d.com/6000.0/Documentation/Manual/StreamingAssets.html) directory to detect whether the game data exists. If the original game data files cannot be detected on desktop clients, the game will pop up a folder selection window for you to select the root directory of the original game installation files on the current device.
@@ -71,7 +88,7 @@ Both games default to the original visual style in URP, preserving the original
The visual effects settings provide independent switches for contact shadows, character lighting, enhanced night fire lighting, and fire shadows. Contact shadows and fire shadows default to enabled on desktop devices. Enhanced fire lighting combines warm lights with a cool ambient tone. Fire shadows also work in dark maze scenes. Desktop defaults to four shadowed fires. Set `Settings.ToonFireShadowBudget` to 0–4 in the debug console. The shadow atlas grows with the budget. Bloom has a separate switch and defaults to enabled only for the original style on desktop.
The screenshots above show the previous toon renderer. Supported story and scene effects in both games use the original data: effect groups, tasks, particles, textures, and models loaded from local CPK archives, rendered with this project's URP shaders and Unity components. Open `PAL3 / PAL3A → Effect Editor` in Unity to select a game, play effects, inspect objects, and edit group tasks and legacy particle curves. Save overrides to `Assets/Resources/Effects/PAL3Overrides.asset` or `PAL3AOverrides.asset` for use in the game. ResourceViewer provides an original effects panel and the commands `Effect.Load <group ID>`, `Effect.Seek <seconds>`, and `Effect.Pause true/false`. Group ID `-1` supports transport points in both games.
The screenshots above show the previous toon renderer. Supported story and scene effects in both games use the original data: effect groups, tasks, particles, textures, and models loaded from local CPK archives, rendered with this project's URP shaders and Unity components. Open `PAL3 / PAL3A → Effect Editor` in Unity to select a game, play effects, inspect objects, and edit group tasks and legacy particle curves. Save overrides to `Assets/Resources/Effects/PAL3Overrides.asset` or `PAL3AOverrides.asset` for use in the game. The resource browser links effect resources to Effect Editor. Group ID `-1` supports transport points in both games.
The current inventory covers all 56 PAL3 and 93 PAL3A story and scene root groups using original data. Transport points reproduce the original disc, two light cones, and colors selected by scene parameters. SPar keyframes, paths, six controller slots, and material blending are implemented independently; raw SPar fields are read-only in the editor. Unsupported types such as battle directors produce diagnostics and will be added alongside their related systems.
+23 -6
View File
@@ -35,24 +35,41 @@
注意:仙剑奇侠传三以及仙剑奇侠传三外传属于原上海软星作品,版权属于软星科技以及大宇公司所有,本项目不包含任何仙剑奇侠传三以及仙剑奇侠传三外传的游戏本体数据。本项目遵循GPL-3.0协议,但仅限于此项目的代码,任何与仙剑奇侠传三或者外传有关的图片,音视频,游戏数据均不在此范围,任何未经版权方许可的情况下使用仙剑奇侠传三或者外传游戏数据进行商业行为都是违法的。
## 主分支当前编译状态
## 最新 PR 编译状态
CI 仅在 Pull Request 上运行;以下徽章显示各工作流最近一次 PR 构建的状态。点击徽章可查看对应的 PR 构建记录。
| 游戏版本 | Windows | Linux | MacOS | Android | iOS |
|-------------------------|---------|-------|-------|---------|-----|
| 仙剑奇侠传三 | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3-mono-windows.yml"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3-mono-windows.yml" alt="Size" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3-mono-linux.yml"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3-mono-linux.yml" alt="Size" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3-mono-macos.yml"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3-mono-macos.yml" alt="Size" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3-mono-android.yml"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3-mono-android.yml" alt="Size" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3-mono-ios.yml"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3-mono-ios.yml" alt="Size" /></a> |
| 仙剑奇侠传三外传:问情篇 | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3a-mono-windows.yml"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3a-mono-windows.yml" alt="Size" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3a-mono-linux.yml"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3a-mono-linux.yml" alt="Size" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3a-mono-macos.yml"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3a-mono-macos.yml" alt="Size" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3a-mono-android.yml"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3a-mono-android.yml" alt="Size" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3a-mono-ios.yml"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3a-mono-ios.yml" alt="Size" /></a> |
| 仙剑奇侠传三 | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3-mono-windows.yml?query=event%3Apull_request"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3-mono-windows.yml?event=pull_request" alt="PR build status" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3-mono-linux.yml?query=event%3Apull_request"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3-mono-linux.yml?event=pull_request" alt="PR build status" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3-mono-macos.yml?query=event%3Apull_request"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3-mono-macos.yml?event=pull_request" alt="PR build status" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3-mono-android.yml?query=event%3Apull_request"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3-mono-android.yml?event=pull_request" alt="PR build status" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3-mono-ios.yml?query=event%3Apull_request"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3-mono-ios.yml?event=pull_request" alt="PR build status" /></a> |
| 仙剑奇侠传三外传:问情篇 | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3a-mono-windows.yml?query=event%3Apull_request"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3a-mono-windows.yml?event=pull_request" alt="PR build status" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3a-mono-linux.yml?query=event%3Apull_request"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3a-mono-linux.yml?event=pull_request" alt="PR build status" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3a-mono-macos.yml?query=event%3Apull_request"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3a-mono-macos.yml?event=pull_request" alt="PR build status" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3a-mono-android.yml?query=event%3Apull_request"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3a-mono-android.yml?event=pull_request" alt="PR build status" /></a> | <a style="text-decoration:none" href="https://github.com/0x7c13/Pal3.Unity/actions/workflows/build-pal3a-mono-ios.yml?query=event%3Apull_request"><img src="https://img.shields.io/github/actions/workflow/status/0x7c13/Pal3.Unity/build-pal3a-mono-ios.yml?event=pull_request" alt="PR build status" /></a> |
## 如何运行项目
使用 [ProjectVersion.txt](ProjectSettings/ProjectVersion.txt) 指定的 Unity 版本打开项目。项目使用 URP Forward+。
因为项目本身不含有仙剑奇侠传三或仙剑奇侠传三外传的游戏数据,所以你需要持有一份仙剑三或外传的游戏原始文件(Steam或者方块游戏获得皆可)。
- 第一次打开Unity项目之后,先双击选择Scenes\Game作为当前场景,然后点播放键即可。如果选择Scenes\ResourceViewer,则会打开游戏资源查看器。
- 第一次打开 Unity 项目之后,双击选择 `Scenes/Game` 作为当前场景,然后点播放键即可。浏览资源使用菜单 `PAL3 / PAL3A → Resource Browser`,无需进入 Play Mode。
- 第一次打开的时候会自动弹出文件夹选择窗口,请选择当前电脑上仙剑奇侠传三(或者外传)的安装文件夹即可。
- 如果你在Steam获取的游戏是繁体中文版的,游戏中的文字会出现乱码,请在游戏设置里选择繁体中文版,然后重启游戏后即可生效。
- 因为原始游戏的过场动画为Bink格式,Unity并不原生支持,所以请自行转码视频为Unity所支持的格式放在游戏根目录下的movie文件夹即可(大部分设备和系统支持.mp4等主流格式视频,Linux下仅支持.webm格式视频)。
- Linux用户可以使用FFmpeg转码视频为.webm格式封装,首先您需要选择Scenes\ResourceViewer场景,然后点击"Extract all .cpk files"按钮来解压所有原始游戏中的.cpk压缩包(包含movie.cpk,所有的Bink动画文件均在这个压缩包中)
- Linux 用户可以使用 FFmpeg 将视频转码为 .webm。先打开 `Resource Browser`,选择原版安装目录并索引,搜索 `ext:bik`,使用 `Original → Export filtered…` 提取视频。超过 64 MiB 的归档资源需用 `Export original…` 单独确认提取。输出保留归档内层级。
```
ffmpeg -i input.mp4 -c:v libvpx -b:v 3M -c:a libvorbis output.webm // vp8 + vorbis
```
## 编辑器资源浏览
菜单 `PAL3 / PAL3A → Resource Browser` 打开可停靠的原生编辑器窗口。选择直接包含 `basedata/` 的数据目录与 936(简体)或 950(繁体)编码,再点击 `Index / Reload`。切换作品使用 `Switch Variant`。
数据目录及其父目录不能含符号链接,请选择链接的真实目标路径;索引也会跳过目录内的符号链接。此限制用于确保导出不会通过路径别名写入原始数据目录。
- 搜索支持路径多词、`-排除词`、`ext:dds`,可按资源类别与归档筛选,上下键选择结果。
- 贴图使用 Unity 原生预览与通道检查,可导出 PNG;模型提供独立视口、原版/Toon、动作选择、播放/时间轴及贴图依赖跳转。
- SCN 检查场景/NPC/物件并跳转关联资源,可预览静态背景与位置标记;NAV 显示分层通行网格和格子数据;LGT 检查光源字段。
- SCE 按块查看指令、变量与对话;GDB 按物品、角色、技能、组合技检索。已解析资源可查看字段和导出 JSON,脚本支持批量导出指令清单或对话。
- 文本支持编码识别、查找、Undo 和另存副本;音频使用原生预览;视频使用当前平台的 Unity 解码器,BIK 仅支持提取;未知资源提供分页十六进制。
原始数据只读,导出保留目录层级且不覆盖已有文件。选择 `Original / Script / Dialogue / Json` 后可批量导出筛选结果,并随时取消。普通预览限制 64 MiB,文本读取限制 4 MiB、窗口编辑限制 60,000 字符。媒体临时提取位于工程相邻的 `workspace/ResourceBrowserMedia/`,换资源或关闭窗口后清理;重新打开窗口时也会清理已退出进程留下的临时目录。特效播放和 override 编辑继续使用 `Effect Editor`。原 `ResourceViewer` 场景已移除。
## 如何在终端设备上运行游戏
- 在打包后的运行时,第一次游戏启动的时候,游戏会搜索 [Application.persistentDataPath](https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Application-persistentDataPath.html) 目录或者 [StreamingAssets](https://docs.unity3d.com/6000.0/Documentation/Manual/StreamingAssets.html) 目录来检测游戏数据是否存在。在桌面版本的游戏中,如果未能检测到原始游戏的数据文件,游戏则会弹出文件夹选择窗口,请选择当前设备上原游戏安装文件的根目录即可。
- 如果上一步未成功,请拷贝整个仙剑奇侠三(或者外传)原游戏目录到 [Application.persistentDataPath](https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Application-persistentDataPath.html) 下即可。注意:如果自行拷贝游戏数据至这个目录的话,如果是仙剑三,文件夹的名称必须为PAL3,如果是仙剑三外传,文件夹名必须为PAL3A。iOS设备请使用iTunes将文件夹共享给游戏应用(这个位置就是persistentDataPath所在的地方)或者在编译时自行打包游戏原始数据到StreamingAssets文件夹下也可。
@@ -70,7 +87,7 @@
「游戏设置 → 画面与特效设置」提供接触阴影、角色光照、增强夜景火光和火光投影四个独立开关,在卡通画风中即时生效。接触阴影和火光投影在桌面设备默认开启,手持设备可按需开启。夜景火光使用暖色灯光与冷色环境底色。火光投影也适用于暗色迷宫,桌面默认四盏,控制台可通过 `Settings.ToonFireShadowBudget` 设置 0–4 盏,阴影图集随预算扩容。泛光可以独立开关,默认仅桌面原版画风开启。
上方截图来自旧版卡通渲染。两作已支持的剧情与场景特效由原版数据驱动,运行时读取本地 CPK 的特效组、任务、粒子、贴图和模型,使用自有 URP shader 与 Unity 原生渲染组件。Unity 菜单 `PAL3 / PAL3A → Effect Editor` 可选择作品、播放、检查对象、修改组任务和旧粒子曲线;覆盖资产分别保存到 `Assets/Resources/Effects/PAL3Overrides.asset` 或 `PAL3AOverrides.asset` 后供游戏读取。ResourceViewer 提供原版特效面板及 `Effect.Load <组ID>`、`Effect.Seek <秒>`、`Effect.Pause true/false` 命令;组 ID `-1` 支持 PAL3/PAL3A 两作传送点。
上方截图来自旧版卡通渲染。两作已支持的剧情与场景特效由原版数据驱动,运行时读取本地 CPK 的特效组、任务、粒子、贴图和模型,使用自有 URP shader 与 Unity 原生渲染组件。Unity 菜单 `PAL3 / PAL3A → Effect Editor` 可选择作品、播放、检查对象、修改组任务和旧粒子曲线;覆盖资产分别保存到 `Assets/Resources/Effects/PAL3Overrides.asset` 或 `PAL3AOverrides.asset` 后供游戏读取。资源浏览器的特效视图可直接打开 Effect Editor;组 ID `-1` 支持 PAL3/PAL3A 两作传送点。
PAL3 已覆盖当前清单中的 56 个剧情/场景根组,PAL3A 已覆盖 93 个,均由原版数据驱动。传送点按原版圆盘、双光锥及场景参数配色播放。SPar 关键帧、路径、六槽控制器和材质混合独立实现,原始 SPar 字段在编辑器中只读。尚未实现的战斗导演等类型会给出诊断,留待对应系统开发时补齐。