mirror of
https://github.com/0x7c13/Pal3.Unity.git
synced 2026-11-26 17:38:10 +08:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3395a7f7a5 | ||
|
|
25579c6c0d | ||
|
|
4cabbd03a7 |
No files matched your search
@@ -0,0 +1,52 @@
|
||||
root = true
|
||||
|
||||
[*.cs]
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
# Match the existing Unity C# sources; keep each file's existing BOM.
|
||||
end_of_line = crlf
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
csharp_new_line_before_open_brace = all
|
||||
csharp_new_line_before_else = true
|
||||
csharp_new_line_before_catch = true
|
||||
csharp_new_line_before_finally = true
|
||||
csharp_new_line_before_members_in_object_initializers = true
|
||||
csharp_new_line_before_members_in_anonymous_types = true
|
||||
csharp_new_line_between_query_expression_clauses = true
|
||||
csharp_indent_block_contents = true
|
||||
csharp_indent_braces = false
|
||||
csharp_indent_case_contents = true
|
||||
csharp_indent_case_contents_when_block = false
|
||||
csharp_indent_switch_labels = true
|
||||
csharp_indent_labels = one_less_than_current
|
||||
|
||||
csharp_space_after_cast = false
|
||||
csharp_space_after_keywords_in_control_flow_statements = true
|
||||
csharp_space_between_method_declaration_parameter_list_parentheses = false
|
||||
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
|
||||
csharp_space_between_method_call_parameter_list_parentheses = false
|
||||
csharp_space_between_method_call_empty_parameter_list_parentheses = false
|
||||
csharp_space_between_parentheses = none
|
||||
csharp_space_before_colon_in_inheritance_clause = true
|
||||
csharp_space_after_colon_in_inheritance_clause = true
|
||||
csharp_space_around_binary_operators = before_and_after
|
||||
csharp_space_before_comma = false
|
||||
csharp_space_after_comma = true
|
||||
csharp_space_before_dot = false
|
||||
csharp_space_after_dot = false
|
||||
csharp_space_before_semicolon_in_for_statement = false
|
||||
csharp_space_after_semicolon_in_for_statement = true
|
||||
csharp_space_before_open_square_brackets = false
|
||||
csharp_space_between_square_brackets = false
|
||||
csharp_space_between_empty_square_brackets = false
|
||||
csharp_preserve_single_line_statements = false
|
||||
csharp_preserve_single_line_blocks = false
|
||||
|
||||
# SDK whitespace formatting does not enforce spacing between members.
|
||||
# These targeted StyleCop rules also run through tools/format-csharp.py.
|
||||
dotnet_diagnostic.SA1107.severity = warning
|
||||
dotnet_diagnostic.SA1502.severity = warning
|
||||
dotnet_diagnostic.SA1507.severity = warning
|
||||
dotnet_diagnostic.SA1516.severity = warning
|
||||
+21
-2
@@ -6,6 +6,26 @@ 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,
|
||||
SA1507 and SA1516 to enforce separate statements, multiline blocks and blank lines
|
||||
between members. StyleCop is restored only into the temporary formatting project.
|
||||
It parses both PAL3 and PAL3A conditional branches without Unity or game data.
|
||||
Run `python3 tools/format-csharp.py` locally to format current changes, then
|
||||
`python3 tools/format-csharp.py --check` to verify them. CI selects PR changes with
|
||||
`--check --base <base-sha>`; `--all` is an explicit full-source audit, not the default.
|
||||
Default and `--base` runs apply formatting only to changed lines and deletion
|
||||
boundaries, preserving existing formatting elsewhere. Explicit file/directory
|
||||
paths and `--all` format whole files. Check mode operates on temporary copies.
|
||||
This checks whitespace and layout, not semantic correctness or Unity behavior.
|
||||
|
||||
Codacy is not part of this repository's CI. Its repository webhook is disabled;
|
||||
there is no Codacy workflow or Codacy-required branch protection check. Re-enabling
|
||||
that external integration would resume its checks independently of these workflows.
|
||||
@@ -15,8 +35,7 @@ The builder CLI is pinned to v0.1.73 so its behavior does not change independent
|
||||
of the workflow. Update and validate this pin together with builder upgrades.
|
||||
|
||||
Keep the committed project configured for PAL3. PAL3A workflows switch their own
|
||||
checkout before building. Public builds reject imported private VFX and legacy Toon assets;
|
||||
do not add them or original game data to CI inputs.
|
||||
checkout before building. Do not add original game data to CI inputs.
|
||||
|
||||
When investigating a failure, inspect the failed job's Unity/build logs first.
|
||||
Retry an isolated runner or network failure after checking the log; fix reproducible
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
name: Code style
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
csharp-format:
|
||||
name: C# formatting (PAL3 and PAL3A)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-dotnet@v5.3.0
|
||||
with:
|
||||
global-json-file: global.json
|
||||
- name: Test formatter enforcement
|
||||
run: python3 tools/tests/test-format-csharp.py
|
||||
- name: Verify changed C# formatting
|
||||
env:
|
||||
BASE_REF: ${{ github.event.pull_request.base.sha }}
|
||||
run: python3 tools/format-csharp.py --check --base "$BASE_REF"
|
||||
+10
-15
@@ -77,20 +77,15 @@ crashlytics-build.properties
|
||||
# Unity StreamingAssets folder
|
||||
/Assets/StreamingAssets
|
||||
|
||||
# 3rd party plugin/assets
|
||||
/Assets/Hovl Studio
|
||||
/Assets/Hovl Studio.meta
|
||||
/Assets/RealToon
|
||||
/Assets/RealToon.meta
|
||||
|
||||
# VFX prefabs that are using 3rd party assets
|
||||
/Assets/Resources/Prefabs/VFX/PAL3/*.prefab
|
||||
/Assets/Resources/Prefabs/VFX/PAL3/*.meta
|
||||
/Assets/Resources/Prefabs/VFX/PAL3A/*.prefab
|
||||
/Assets/Resources/Prefabs/VFX/PAL3A/*.meta
|
||||
|
||||
# Materials that are using 3rd party assets
|
||||
/Assets/Resources/Materials/
|
||||
|
||||
# VS Conde config file
|
||||
.vsconfig
|
||||
|
||||
# Local asset imports
|
||||
/Assets/Hovl Studio/
|
||||
/Assets/Hovl Studio.meta
|
||||
/Assets/RealToon/
|
||||
/Assets/RealToon.meta
|
||||
/Assets/Resources/Prefabs/VFX/
|
||||
/Assets/Resources/Prefabs/VFX.meta
|
||||
/Assets/Resources/Materials/
|
||||
/Assets/Resources/Materials.meta
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,7 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e65c4b938f18e6c4a86dc379157fac65
|
||||
PrefabImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,8 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2eaeb845461401e488e4640caf779ddf
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,45 +0,0 @@
|
||||
因为当前特效的实现方式使用了第三方插件和素材,所以此文件夹内的所有prefab均添加进了gitignore里。
|
||||
请联系作者了解插件获取方式和特效prefab的获取方式。
|
||||
|
||||
0 => 传送法阵特效
|
||||
|
||||
15 => 单人传送特效
|
||||
98 => 重楼施法帮龙葵恢复肉身时的特效
|
||||
175 => 邪剑仙迷倒众人的特效
|
||||
224 => 丁小侠剧情狼妖受击特效
|
||||
251 => 邪剑仙变身特效
|
||||
252 => 邪剑仙传送离开时的特效
|
||||
254 => 重楼传送法术特效
|
||||
255 => 龙葵穿衣服的特效
|
||||
256 => 龙葵治疗他人特效
|
||||
257 => 治疗咒施法特效
|
||||
259 => 大型传送法施法前奏特效
|
||||
260 => 大型传送法阵特效收尾
|
||||
261 => 大型传送法阵特效开始
|
||||
262 => 重楼当剑的时候剑插入地面的火光特效
|
||||
263 => 火鬼王消失特效
|
||||
264 => 古藤精施法特效
|
||||
265 => 人物受到法术作用时候的特效
|
||||
266 => 邪剑仙施法特效
|
||||
270 => 天鬼皇复活后灵魂出窍特效
|
||||
275 => 重楼创建的用来禁锢雪见/龙葵的法阵特效
|
||||
276 => 迴魂施法结束特效
|
||||
277 => 迴魂施法完全结束特效
|
||||
278 => 迴魂施法特效
|
||||
290 => 雪见传送出现时特效
|
||||
295 => 重楼施法治疗特效
|
||||
297 => 紫萱施法召唤水灵特效
|
||||
337 => 古藤精风系法术特效
|
||||
341 => 邪剑仙给镇妖剑施法特效
|
||||
368 => 雷击单体施法特效
|
||||
369 => 雷击范围施法特效
|
||||
376 => 紫萱的土系法术特效
|
||||
389 => 紫萱给江姑娘施法特效
|
||||
452 => 花楹治疗他人特效
|
||||
453 => 人物施法蓄力时的特效
|
||||
454 => 龙葵施法让众人御剑飞行的特效
|
||||
456 => 老婆婆施法特效
|
||||
457 => 夕瑶给景天施法时的特效
|
||||
458 => 灵力溢出特效
|
||||
467 => 邪剑仙灰飞烟灭特效
|
||||
468 => 蓝龙葵变红龙葵的特效
|
||||
@@ -1,7 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 815b64a4a03e7b949bd85e1e5c19deb3
|
||||
TextScriptImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,67 +0,0 @@
|
||||
因为当前特效的实现方式使用了第三方插件和素材,所以此文件夹内的所有prefab均添加进了gitignore里。
|
||||
请联系作者了解插件获取方式和特效prefab的获取方式。
|
||||
|
||||
0 => 传送法阵特效
|
||||
9 => 茅山道士封印法术特效
|
||||
40 => 单体风咒特效
|
||||
50 => 单体雷咒特效
|
||||
91 => 封印法术特效
|
||||
157 => 角色传送出现特效
|
||||
164 => 南宫煌变身狼形态时的特效
|
||||
170 => 王蓬絮变身特效
|
||||
171 => 人物施法特效
|
||||
172 => 人物受到法术作用时候的特效
|
||||
173 => 人物受到法术作用时候的特效
|
||||
174 => 治疗特效
|
||||
175 => 茅山术士打乱三杯盏特效
|
||||
176 => 南宫煌打乱三杯盏特效
|
||||
177 => 角色传送消失时的特效
|
||||
178 => 南宫煌使关桃子的笼子消失的特效
|
||||
179 => 南宫煌变出法桌的特效
|
||||
181 => 南宫煌变出小东西的特效
|
||||
182 => 南宫煌变出大东西的特效
|
||||
186 => 大石块砸下后的尘土特效
|
||||
189 => 地脉石门封印打开时的特效
|
||||
198 => 南宫煌变出东西的特效
|
||||
201 => 魁妖变小特效
|
||||
205 => 照妖镜发光的特效
|
||||
209 => 五灵轮特效
|
||||
211 => 洒金笺特效
|
||||
230 => 重楼施法消灭怪物的特效
|
||||
254 => 重楼传送特效
|
||||
257 => 隔空取物特效
|
||||
258 => 迴魂传送特效
|
||||
259 => 大型传送法施法前奏特效
|
||||
260 => 大型传送法阵特效收尾
|
||||
261 => 大型传送法阵特效开始
|
||||
281 => 角色传送消失时的特效
|
||||
282 => 雷咒特效
|
||||
283 => 物品消失时的特效
|
||||
285 => 南宫煌施法特效
|
||||
287 => 土灵珠特效
|
||||
289 => 血魂姬施法特效
|
||||
290 => 回复法阵特效
|
||||
292 => 五灵轮发光特效
|
||||
299 => 重楼传送众人特效
|
||||
314 => 倾国银弹波特效
|
||||
315 => 南宫煌切换为人形态特效
|
||||
316 => 魔物出现特效
|
||||
318 => 千凝魔艮特效
|
||||
320 => 幽娘变身特效
|
||||
322 => 幽娘吸收怨气特效
|
||||
323 => 幽娘收集怨气特效
|
||||
325 => 陆北亭变身特效
|
||||
328 => 风雅颂开心的特效
|
||||
333 => 感月出现特效
|
||||
355 => 王蓬絮治疗特效
|
||||
359 => 蝎魃消失特效
|
||||
360 => 星璇给南宫煌输入内力时的特效
|
||||
367 => 五毒珠治疗特效
|
||||
388 => 迴魂传送特效
|
||||
389 => 迴魂传送特效
|
||||
397 => 燎日变身特效
|
||||
401 => 魔尊帮星璇灵肉合一的特效
|
||||
404 => 思堂消失特效
|
||||
408 => 星璇燎日变换时特效
|
||||
424 => 王蓬絮对南宫煌施法特效
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f1d950c46b3119043a1919074fdc27c5
|
||||
TextScriptImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,78 @@
|
||||
// ------------------------------------------------------------------------
|
||||
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
|
||||
// See LICENSE file in the project root for license information.
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
Shader "Pal3/OriginalEffect"
|
||||
{
|
||||
Properties
|
||||
{
|
||||
_MainTex ("Texture", 2D) = "white" {}
|
||||
[Enum(UnityEngine.Rendering.BlendMode)] _SrcBlend ("Source blend", Float) = 1
|
||||
[Enum(UnityEngine.Rendering.BlendMode)] _DstBlend ("Destination blend", Float) = 1
|
||||
[Enum(UnityEngine.Rendering.CompareFunction)] _ZTest ("Depth test", Float) = 4
|
||||
[Enum(UnityEngine.Rendering.CullMode)] _Cull ("Cull", Float) = 0
|
||||
_AlphaMode ("Original alpha operation", Float) = 0
|
||||
}
|
||||
SubShader
|
||||
{
|
||||
Tags
|
||||
{
|
||||
"RenderPipeline" = "UniversalPipeline"
|
||||
"Queue" = "Transparent"
|
||||
"RenderType" = "Transparent"
|
||||
}
|
||||
Pass
|
||||
{
|
||||
Tags { "LightMode" = "SRPDefaultUnlit" }
|
||||
Blend [_SrcBlend] [_DstBlend]
|
||||
ZTest [_ZTest]
|
||||
ZWrite Off
|
||||
Cull [_Cull]
|
||||
HLSLPROGRAM
|
||||
#pragma vertex Vert
|
||||
#pragma fragment Frag
|
||||
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
|
||||
struct Attributes
|
||||
{
|
||||
float3 positionOS : POSITION;
|
||||
float2 uv : TEXCOORD0;
|
||||
half4 color : COLOR;
|
||||
};
|
||||
struct Varyings
|
||||
{
|
||||
float4 positionCS : SV_POSITION;
|
||||
float2 uv : TEXCOORD0;
|
||||
half4 color : COLOR;
|
||||
};
|
||||
TEXTURE2D(_MainTex);
|
||||
SAMPLER(sampler_MainTex);
|
||||
CBUFFER_START(UnityPerMaterial)
|
||||
float _AlphaMode;
|
||||
CBUFFER_END
|
||||
Varyings Vert(Attributes i)
|
||||
{
|
||||
Varyings o;
|
||||
o.positionCS = TransformObjectToHClip(i.positionOS);
|
||||
o.uv = i.uv;
|
||||
o.color = i.color;
|
||||
return o;
|
||||
}
|
||||
half4 Frag(Varyings i) : SV_Target
|
||||
{
|
||||
half4 tex = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.uv);
|
||||
half4 col = tex * i.color;
|
||||
if (_AlphaMode > 1.5)
|
||||
{
|
||||
col.a = tex.a;
|
||||
}
|
||||
else if (_AlphaMode > 0.5)
|
||||
{
|
||||
col.a = saturate(tex.a + i.color.a);
|
||||
}
|
||||
return col;
|
||||
}
|
||||
ENDHLSL
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
fileFormatVersion: 2
|
||||
guid: dd7af60dc97334317a8bf7d560ba0f71
|
||||
ShaderImporter:
|
||||
externalObjects: {}
|
||||
defaultTextures: []
|
||||
nonModifiableTextures: []
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -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}
|
||||
@@ -1,7 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9fc0d4010bbf28b4594072e72b8655ab
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,696 @@
|
||||
// ------------------------------------------------------------------------
|
||||
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
|
||||
// See LICENSE file in the project root for license information.
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
namespace Editor
|
||||
{
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Pal3.Core.DataReader.Cpk;
|
||||
using Pal3.Core.DataReader.Data;
|
||||
using Pal3.Core.DataReader.Par;
|
||||
using Pal3.Core.FileSystem;
|
||||
using Pal3.Game.Effect.Original;
|
||||
using UnityEditor;
|
||||
using UnityEditor.SceneManagement;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
using UnityEngine.Rendering.Universal;
|
||||
using UnityEngine.SceneManagement;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
public sealed class EffectEditor : EditorWindow
|
||||
{
|
||||
private OriginalEffectResources _resources;
|
||||
private OriginalEffectPlayer _player;
|
||||
private OriginalPortalEffect _portal;
|
||||
private uint _portalType;
|
||||
[SerializeField] private OriginalEffectOverrides _edits;
|
||||
[SerializeField] private string _assetPath = "", _savedJson;
|
||||
private GameObject _root;
|
||||
private Scene _scene;
|
||||
private Camera _camera;
|
||||
private RenderTexture _target;
|
||||
private string _dataPath, _search = "", _error;
|
||||
[SerializeField] private bool _pal3a;
|
||||
|
||||
private string Variant => _pal3a ? "PAL3A" : "PAL3";
|
||||
|
||||
private int _codepage = 936;
|
||||
[SerializeField] private int _id = 98, _objectIndex;
|
||||
private Vector2 _listScroll, _inspectorScroll, _orbit = new(135, 15);
|
||||
private float _distance = 14, _speed = 1, _duration = 15;
|
||||
[SerializeField] private float _time;
|
||||
private bool _playing, _loop;
|
||||
private uint _seed = 1;
|
||||
private bool _emitterCurve;
|
||||
private int _particleIndex, _curveIndex;
|
||||
private double _lastUpdate;
|
||||
private string _previewJson;
|
||||
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");
|
||||
window.ChangeVariant(true);
|
||||
}
|
||||
|
||||
private void ChangeVariant(bool pal3a)
|
||||
{
|
||||
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;
|
||||
_time = 0;
|
||||
LoadOverrides(Resources.Load<OriginalEffectOverrides>($"Effects/{Variant}Overrides"));
|
||||
LoadPreferences();
|
||||
LoadData();
|
||||
}
|
||||
|
||||
private void LoadPreferences()
|
||||
{
|
||||
_dataPath = EditorPrefs.GetString($"{Variant}.OriginalEffect.DataPath", Path.GetFullPath(Path.Combine(Application.dataPath, $"../../Game Data/{Variant}")));
|
||||
_codepage = EditorPrefs.GetInt($"{Variant}.OriginalEffect.Codepage", 936) == 950 ? 950 : 936;
|
||||
}
|
||||
|
||||
public void CreateGUI() => rootVisualElement.Add(new IMGUIContainer(DrawWindow) { style = { flexGrow = 1 } });
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
minSize = new Vector2(1050, 640);
|
||||
LoadPreferences();
|
||||
if (_edits == null)
|
||||
LoadOverrides(Resources.Load<OriginalEffectOverrides>($"Effects/{Variant}Overrides"));
|
||||
_edits.hideFlags = HideFlags.HideInHierarchy | HideFlags.DontSave;
|
||||
saveChangesMessage = "Save the original effect overrides before closing?";
|
||||
_scene = EditorSceneManager.NewPreviewScene();
|
||||
var cameraObject = new GameObject("Effect preview camera") { hideFlags = HideFlags.HideAndDontSave };
|
||||
SceneManager.MoveGameObjectToScene(cameraObject, _scene);
|
||||
_camera = cameraObject.AddComponent<Camera>();
|
||||
_camera.enabled = false;
|
||||
_camera.clearFlags = CameraClearFlags.SolidColor;
|
||||
_camera.backgroundColor = new Color(0.07f, 0.08f, 0.1f);
|
||||
_camera.fieldOfView = 40;
|
||||
_camera.nearClipPlane = 0.01f;
|
||||
_camera.farClipPlane = 500;
|
||||
_camera.scene = _scene;
|
||||
_lastUpdate = EditorApplication.timeSinceStartup;
|
||||
EditorApplication.update += Tick;
|
||||
Undo.undoRedoPerformed += RefreshAfterUndo;
|
||||
if (Directory.Exists(_dataPath))
|
||||
LoadData();
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
EditorApplication.update -= Tick;
|
||||
Undo.undoRedoPerformed -= RefreshAfterUndo;
|
||||
ClearPreview();
|
||||
_resources?.Dispose();
|
||||
_resources = null;
|
||||
if (_target != null)
|
||||
{
|
||||
_target.Release();
|
||||
DestroyImmediate(_target);
|
||||
}
|
||||
if (_scene.IsValid())
|
||||
EditorSceneManager.ClosePreviewScene(_scene);
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
if (_edits != null)
|
||||
{
|
||||
Undo.ClearUndo(_edits);
|
||||
DestroyImmediate(_edits);
|
||||
}
|
||||
}
|
||||
|
||||
private void LoadOverrides(OriginalEffectOverrides asset)
|
||||
{
|
||||
if (_edits != null)
|
||||
{
|
||||
Undo.ClearUndo(_edits);
|
||||
DestroyImmediate(_edits);
|
||||
}
|
||||
_edits = asset != null ? Instantiate(asset) : CreateInstance<OriginalEffectOverrides>();
|
||||
_edits.hideFlags = HideFlags.HideInHierarchy | HideFlags.DontSave;
|
||||
_assetPath = asset != null ? AssetDatabase.GetAssetPath(asset) : "";
|
||||
_savedJson = JsonUtility.ToJson(_edits);
|
||||
hasUnsavedChanges = false;
|
||||
}
|
||||
|
||||
private void MarkChanged() => hasUnsavedChanges = JsonUtility.ToJson(_edits) != _savedJson;
|
||||
|
||||
public override void SaveChanges()
|
||||
{
|
||||
if (SaveOverrides())
|
||||
base.SaveChanges();
|
||||
}
|
||||
|
||||
public override void DiscardChanges()
|
||||
{
|
||||
LoadOverrides(_assetPath.Length > 0 ? AssetDatabase.LoadAssetAtPath<OriginalEffectOverrides>(_assetPath) : null);
|
||||
base.DiscardChanges();
|
||||
RefreshAfterUndo();
|
||||
}
|
||||
|
||||
private bool CanReplaceEdits()
|
||||
{
|
||||
if (!hasUnsavedChanges)
|
||||
return true;
|
||||
int choice = EditorUtility.DisplayDialogComplex("Original effect overrides", "Save your current edits before loading another asset?", "Save", "Cancel", "Discard");
|
||||
return choice == 2 || choice == 0 && SaveOverrides();
|
||||
}
|
||||
|
||||
private bool SaveOverrides()
|
||||
{
|
||||
string path = EditorUtility.SaveFilePanelInProject($"Save {Variant} effect overrides",
|
||||
_assetPath.Length > 0 ? Path.GetFileNameWithoutExtension(_assetPath) : $"{Variant}Overrides", "asset",
|
||||
$"Use Assets/Resources/Effects/{Variant}Overrides.asset for runtime loading.");
|
||||
if (path.Length == 0)
|
||||
return false;
|
||||
var existing = AssetDatabase.LoadMainAssetAtPath(path);
|
||||
if (existing != null && existing is not OriginalEffectOverrides)
|
||||
{
|
||||
_error = "Choose an OriginalEffectOverrides asset or a new path.";
|
||||
return false;
|
||||
}
|
||||
var saved = existing as OriginalEffectOverrides;
|
||||
if (saved != null)
|
||||
{
|
||||
Undo.RecordObject(saved, $"Save {Variant} effect overrides");
|
||||
EditorUtility.CopySerialized(_edits, saved);
|
||||
saved.hideFlags = HideFlags.None;
|
||||
EditorUtility.SetDirty(saved);
|
||||
}
|
||||
else
|
||||
{
|
||||
saved = Instantiate(_edits);
|
||||
saved.hideFlags = HideFlags.None;
|
||||
AssetDatabase.CreateAsset(saved, path);
|
||||
}
|
||||
saved.name = Path.GetFileNameWithoutExtension(path);
|
||||
EditorUtility.SetDirty(saved);
|
||||
AssetDatabase.SaveAssets();
|
||||
_assetPath = path;
|
||||
_savedJson = JsonUtility.ToJson(_edits);
|
||||
hasUnsavedChanges = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private void LoadData()
|
||||
{
|
||||
float time = _time;
|
||||
ClearPreview();
|
||||
_resources?.Dispose();
|
||||
_resources = null;
|
||||
_error = null;
|
||||
try
|
||||
{
|
||||
var hash = new Crc32Hash();
|
||||
hash.Init();
|
||||
var fs = new CpkFileSystem(_dataPath, hash, _codepage);
|
||||
fs.Mount("basedata/basedata.cpk", _codepage);
|
||||
_resources = new OriginalEffectResources(fs, _codepage);
|
||||
if (_resources.GameVariant != Variant)
|
||||
throw new InvalidDataException($"The selected directory contains {_resources.GameVariant} data; select the matching variant first.");
|
||||
EditorPrefs.SetString($"{Variant}.OriginalEffect.DataPath", _dataPath);
|
||||
Restart();
|
||||
Seek(time);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_resources?.Dispose();
|
||||
_resources = null;
|
||||
_error = ex.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
private void ClearPreview()
|
||||
{
|
||||
if (_root != null)
|
||||
DestroyImmediate(_root);
|
||||
_player = null;
|
||||
_portal = null;
|
||||
}
|
||||
|
||||
private void Restart()
|
||||
{
|
||||
ClearPreview();
|
||||
_time = 0;
|
||||
_pendingSeek = null;
|
||||
_error = null;
|
||||
_previewJson = JsonUtility.ToJson(_edits);
|
||||
if (_resources == null)
|
||||
return;
|
||||
try
|
||||
{
|
||||
_root = new GameObject("Original effect preview") { hideFlags = HideFlags.HideAndDontSave };
|
||||
SceneManager.MoveGameObjectToScene(_root, _scene);
|
||||
if (_id < 0)
|
||||
{
|
||||
_portal = _root.AddComponent<OriginalPortalEffect>();
|
||||
_portal.AutoAdvance = false;
|
||||
_portal.Initialize(_resources, _portalType);
|
||||
}
|
||||
else
|
||||
{
|
||||
string[] issues = _resources.Diagnose(_id, _edits);
|
||||
if (issues.Length > 0)
|
||||
_error = string.Join("\n", issues);
|
||||
else
|
||||
{
|
||||
_player = _root.AddComponent<OriginalEffectPlayer>();
|
||||
_player.AutoAdvance = false;
|
||||
_player.Initialize(_resources, _id, _seed, _edits);
|
||||
_player.Loop = false;
|
||||
if (_player.Error != null)
|
||||
_error = _player.Error;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ClearPreview();
|
||||
_error = ex.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
private void Tick()
|
||||
{
|
||||
double now = EditorApplication.timeSinceStartup;
|
||||
float dt = Mathf.Min(0.1f, (float)(now - _lastUpdate));
|
||||
_lastUpdate = now;
|
||||
if (_pendingSeek.HasValue && now >= _seekAfter)
|
||||
{
|
||||
Seek(_pendingSeek.Value);
|
||||
Repaint();
|
||||
}
|
||||
if (_playing)
|
||||
{
|
||||
Advance(dt * _speed);
|
||||
if (_time >= _duration)
|
||||
{
|
||||
if (_loop)
|
||||
Restart();
|
||||
else
|
||||
_playing = false;
|
||||
}
|
||||
Repaint();
|
||||
}
|
||||
}
|
||||
|
||||
private void Advance(float delta)
|
||||
{
|
||||
_time += delta;
|
||||
_player?.Advance(delta);
|
||||
_portal?.Sample(_time);
|
||||
}
|
||||
|
||||
private void Seek(float time)
|
||||
{
|
||||
_pendingSeek = null;
|
||||
_time = time;
|
||||
_player?.Seek(time);
|
||||
_portal?.Sample(time);
|
||||
}
|
||||
|
||||
private void QueueSeek(float time)
|
||||
{
|
||||
_playing = false;
|
||||
_pendingSeek = time;
|
||||
_seekAfter = EditorApplication.timeSinceStartup + 0.05;
|
||||
Repaint();
|
||||
}
|
||||
|
||||
private void RefreshAfterUndo()
|
||||
{
|
||||
MarkChanged();
|
||||
if (_previewJson == JsonUtility.ToJson(_edits))
|
||||
return;
|
||||
float time = _time;
|
||||
Restart();
|
||||
Seek(time);
|
||||
Repaint();
|
||||
}
|
||||
|
||||
private void DrawWindow()
|
||||
{
|
||||
using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar))
|
||||
{
|
||||
int variant = EditorGUILayout.Popup(_pal3a ? 1 : 0, new[] { "PAL3", "PAL3A" }, GUILayout.Width(80));
|
||||
if ((variant == 1) != _pal3a)
|
||||
ChangeVariant(variant == 1);
|
||||
_dataPath = EditorGUILayout.TextField(_dataPath);
|
||||
int codepage = EditorGUILayout.Popup(_codepage == 950 ? 1 : 0, new[] { "GBK (936)", "Big5 (950)" }, GUILayout.Width(105)) == 0 ? 936 : 950;
|
||||
if (codepage != _codepage)
|
||||
{
|
||||
_codepage = codepage;
|
||||
EditorPrefs.SetInt($"{Variant}.OriginalEffect.Codepage", _codepage);
|
||||
LoadData();
|
||||
}
|
||||
if (GUILayout.Button("Browse", EditorStyles.toolbarButton, GUILayout.Width(60)))
|
||||
{
|
||||
string path = EditorUtility.OpenFolderPanel($"{Variant} data (contains basedata)", _dataPath, "");
|
||||
if (path.Length > 0)
|
||||
{
|
||||
_dataPath = path;
|
||||
LoadData();
|
||||
}
|
||||
}
|
||||
if (GUILayout.Button("Reload", EditorStyles.toolbarButton, GUILayout.Width(55)))
|
||||
LoadData();
|
||||
}
|
||||
var asset = _assetPath.Length > 0 ? AssetDatabase.LoadAssetAtPath<OriginalEffectOverrides>(_assetPath) : null;
|
||||
var selected = (OriginalEffectOverrides)EditorGUILayout.ObjectField("Overrides", asset, typeof(OriginalEffectOverrides), false);
|
||||
if (selected != asset && CanReplaceEdits())
|
||||
{
|
||||
LoadOverrides(selected);
|
||||
Restart();
|
||||
}
|
||||
if (_resources == null)
|
||||
{
|
||||
EditorGUILayout.HelpBox(_error ?? "Choose the PAL3 game data directory.", MessageType.Info);
|
||||
return;
|
||||
}
|
||||
using (new EditorGUILayout.HorizontalScope())
|
||||
{
|
||||
using (new EditorGUILayout.VerticalScope(GUILayout.Width(185)))
|
||||
{
|
||||
_search = EditorGUILayout.TextField(_search, EditorStyles.toolbarSearchField);
|
||||
_listScroll = EditorGUILayout.BeginScrollView(_listScroll);
|
||||
if (GUILayout.Button("Scene: Transport point"))
|
||||
Select(-1);
|
||||
for (int id = 0; id < _resources.Definitions.Groups.Length; id++)
|
||||
{
|
||||
EffectGroup g = _resources.Definitions.Groups[id];
|
||||
if (g.Objects.Length == 0)
|
||||
continue;
|
||||
string label = $"{id} ({g.Objects.Length})";
|
||||
if (_search.Length > 0 && !label.Contains(_search) && !g.Objects.Any(o => _resources.Definitions.TryGetType(o.TypeCrc, out var d) && d.TypeName.Contains(_search)))
|
||||
continue;
|
||||
if (GUILayout.Toggle(_id == id, label, "Button") && _id != id)
|
||||
Select(id);
|
||||
}
|
||||
EditorGUILayout.EndScrollView();
|
||||
}
|
||||
using (new EditorGUILayout.VerticalScope())
|
||||
{
|
||||
if (_id < 0 && _pal3a)
|
||||
{
|
||||
int style = EditorGUILayout.Popup("Transport style", (int)_portalType, new[] { "Default", "1 (trans_s)", "2 (trans_m)", "3 (trans_l)", "4 (trans_f)", "5 (trans_t)", "6 (trans_p)" });
|
||||
if ((uint)style != _portalType)
|
||||
{
|
||||
_portalType = (uint)style;
|
||||
Restart();
|
||||
}
|
||||
}
|
||||
using (new EditorGUILayout.HorizontalScope())
|
||||
{
|
||||
if (GUILayout.Button(_playing ? "Pause" : "Play", GUILayout.Width(60)))
|
||||
_playing = !_playing;
|
||||
if (GUILayout.Button("Reset", GUILayout.Width(55)))
|
||||
Restart();
|
||||
if (GUILayout.Button("Step", GUILayout.Width(50)))
|
||||
{
|
||||
_playing = false;
|
||||
Advance(OriginalEffectPlayer.FixedStep);
|
||||
Repaint();
|
||||
}
|
||||
GUILayout.Label("Speed", GUILayout.Width(40));
|
||||
_speed = EditorGUILayout.FloatField(_speed, GUILayout.Width(45));
|
||||
_speed = float.IsFinite(_speed) ? Mathf.Clamp(_speed, 0, 16) : 1;
|
||||
_loop = GUILayout.Toggle(_loop, "Loop");
|
||||
}
|
||||
Rect preview = GUILayoutUtility.GetRect(200, 200, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
|
||||
DrawPreview(preview);
|
||||
float displayedTime = _pendingSeek ?? _time;
|
||||
float time = EditorGUILayout.Slider("Time", displayedTime, 0, _duration);
|
||||
if (Mathf.Abs(time - displayedTime) > 0.00001f)
|
||||
QueueSeek(time);
|
||||
using (new EditorGUILayout.HorizontalScope())
|
||||
{
|
||||
_duration = EditorGUILayout.FloatField("Preview duration", _duration);
|
||||
_duration = float.IsFinite(_duration) ? Mathf.Clamp(_duration, 0.1f, 600) : 15;
|
||||
uint seed = (uint)Mathf.Max(1, EditorGUILayout.IntField("Seed", (int)_seed));
|
||||
if (seed != _seed)
|
||||
{
|
||||
_seed = seed;
|
||||
Restart();
|
||||
}
|
||||
}
|
||||
EditorGUILayout.LabelField($"Objects: {_player?.NodeCount ?? 0} Quads/particles: {_player?.QuadCount ?? 0} {_player?.Error}");
|
||||
EditorGUILayout.LabelField("Drag to orbit · Scroll to zoom", EditorStyles.miniLabel);
|
||||
if (_error != null)
|
||||
EditorGUILayout.HelpBox(_error, MessageType.Warning);
|
||||
}
|
||||
using (new EditorGUILayout.VerticalScope(GUILayout.Width(310)))
|
||||
DrawInspector();
|
||||
}
|
||||
}
|
||||
|
||||
private void Select(int id)
|
||||
{
|
||||
_id = id;
|
||||
_objectIndex = 0;
|
||||
Restart();
|
||||
}
|
||||
|
||||
private void DrawPreview(Rect rect)
|
||||
{
|
||||
Event e = Event.current;
|
||||
if (rect.Contains(e.mousePosition))
|
||||
{
|
||||
if (e.type == EventType.MouseDrag && e.button == 0)
|
||||
{
|
||||
_orbit += e.delta * new Vector2(0.5f, -0.5f);
|
||||
e.Use();
|
||||
Repaint();
|
||||
}
|
||||
if (e.type == EventType.ScrollWheel)
|
||||
{
|
||||
_distance = Mathf.Clamp(_distance * Mathf.Exp(e.delta.y * 0.08f), 0.3f, 200);
|
||||
e.Use();
|
||||
Repaint();
|
||||
}
|
||||
}
|
||||
if (e.type != EventType.Repaint || rect.width < 1 || rect.height < 1)
|
||||
return;
|
||||
int w = Mathf.Max(1, (int)rect.width), h = Mathf.Max(1, (int)rect.height);
|
||||
if (_target == null || _target.width != w || _target.height != h)
|
||||
{
|
||||
if (_target != null)
|
||||
{
|
||||
_target.Release();
|
||||
DestroyImmediate(_target);
|
||||
}
|
||||
_target = new RenderTexture(w, h, 24) { hideFlags = HideFlags.HideAndDontSave };
|
||||
_target.Create();
|
||||
}
|
||||
_camera.transform.position = Quaternion.Euler(_orbit.y, _orbit.x, 0) * new Vector3(0, 0, -_distance) + Vector3.up * 1.5f;
|
||||
_camera.transform.LookAt(Vector3.up * 1.5f);
|
||||
_camera.aspect = (float)w / h;
|
||||
_player?.Render(_camera);
|
||||
RenderPipeline.SubmitRenderRequest(_camera, new UniversalRenderPipeline.SingleCameraRequest { destination = _target });
|
||||
GUI.DrawTexture(rect, _target, ScaleMode.StretchToFill, false);
|
||||
GUI.Label(new Rect(rect.x + 8, rect.y + 8, rect.width - 16, 25), $"{Variant} effect data", EditorStyles.whiteBoldLabel);
|
||||
}
|
||||
|
||||
private void DrawInspector()
|
||||
{
|
||||
EditorGUILayout.LabelField("Object / task parameters", EditorStyles.boldLabel);
|
||||
if (_id < 0)
|
||||
{
|
||||
EditorGUILayout.HelpBox("MXTransport: original two cones and rotating plane. This is separate from flexeff group 0.", MessageType.Info);
|
||||
return;
|
||||
}
|
||||
EffectGroup group = _resources.Definitions.Groups[_id];
|
||||
if (group.Objects.Length == 0)
|
||||
return;
|
||||
_objectIndex = EditorGUILayout.IntSlider("Object", _objectIndex, 0, group.Objects.Length - 1);
|
||||
EffectGroupObject source = group.Objects[_objectIndex];
|
||||
_resources.Definitions.TryGetType(source.TypeCrc, out EffectDefinition d);
|
||||
EditorGUILayout.LabelField($"{d.TypeName} / {EffectClass.Name(d.ClassNameCrc)}");
|
||||
EditorGUILayout.SelectableLabel(d.TextureName ?? "", GUILayout.Height(35));
|
||||
OriginalEffectObjectOverride edit = _edits.Find(_id, _objectIndex);
|
||||
if (edit == null && GUILayout.Button("Edit this object"))
|
||||
{
|
||||
Undo.RecordObject(_edits, "Edit original effect");
|
||||
edit = new OriginalEffectObjectOverride
|
||||
{
|
||||
GroupId = _id,
|
||||
ObjectIndex = _objectIndex,
|
||||
Definition = JsonUtility.FromJson<EffectDefinition>(JsonUtility.ToJson(d)),
|
||||
Tasks = source.Tasks.Select(t => JsonUtility.FromJson<EffectTask>(JsonUtility.ToJson(t))).ToArray()
|
||||
};
|
||||
_edits.Objects.Add(edit);
|
||||
MarkChanged();
|
||||
}
|
||||
_inspectorScroll = EditorGUILayout.BeginScrollView(_inspectorScroll);
|
||||
if (edit != null)
|
||||
{
|
||||
var so = new SerializedObject(_edits);
|
||||
so.Update();
|
||||
SerializedProperty entry = so.FindProperty("Objects").GetArrayElementAtIndex(_edits.Objects.IndexOf(edit));
|
||||
EditorGUILayout.PropertyField(entry.FindPropertyRelative("Hidden"));
|
||||
EditorGUILayout.PropertyField(entry.FindPropertyRelative("Definition"), true);
|
||||
EditorGUILayout.PropertyField(entry.FindPropertyRelative("Tasks"), true);
|
||||
if (so.ApplyModifiedProperties())
|
||||
{
|
||||
MarkChanged();
|
||||
float time = _time;
|
||||
Restart();
|
||||
Seek(time);
|
||||
}
|
||||
}
|
||||
else
|
||||
foreach (EffectTask t in source.Tasks)
|
||||
EditorGUILayout.LabelField($"{t.StartTime:0.###}s + {t.Duration:0.###}s loops={t.RequireLoops}");
|
||||
EffectDefinition effective = edit?.Definition ?? d;
|
||||
if (EffectClass.Name(effective.ClassNameCrc) == "S-Particle")
|
||||
{
|
||||
try
|
||||
{
|
||||
SparFile spar = _resources.Spar(effective.ParticleFileName);
|
||||
EditorGUILayout.LabelField($"SPar: {spar.Groups.Length} groups / shader {spar.Shader}");
|
||||
foreach (SparGroup sg in spar.Groups)
|
||||
{
|
||||
EditorGUILayout.LabelField($"{sg.Name}: capacity {sg.Capacity}, {sg.Keyframes.Length} keys", EditorStyles.wordWrappedLabel);
|
||||
EditorGUILayout.SelectableLabel(sg.Texture, GUILayout.Height(30));
|
||||
}
|
||||
EditorGUILayout.HelpBox("Native SPar playback: keyframes, emitter paths, particle controllers and original shader blending. SPar fields are read-only here.", MessageType.Info);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
EditorGUILayout.HelpBox(ex.Message, MessageType.Warning);
|
||||
}
|
||||
}
|
||||
if (EffectClass.Name(effective.ClassNameCrc) == "particle")
|
||||
DrawParticleCurves(effective.ParticleFileName);
|
||||
EditorGUILayout.EndScrollView();
|
||||
if (GUILayout.Button("Save overrides for game…"))
|
||||
SaveOverrides();
|
||||
if (GUILayout.Button("Discard edits for this object") && edit != null)
|
||||
{
|
||||
Undo.RecordObject(_edits, "Discard original effect override");
|
||||
_edits.Objects.Remove(edit);
|
||||
MarkChanged();
|
||||
Restart();
|
||||
}
|
||||
}
|
||||
|
||||
private void DrawParticleCurves(string path)
|
||||
{
|
||||
EditorGUILayout.Space();
|
||||
EditorGUILayout.LabelField("Particle resource curves", EditorStyles.boldLabel);
|
||||
ParticleFile file;
|
||||
try
|
||||
{
|
||||
file = _resources.Particle(path);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
EditorGUILayout.HelpBox(ex.Message, MessageType.Warning);
|
||||
return;
|
||||
}
|
||||
_emitterCurve = EditorGUILayout.Toggle("Emitter curves", _emitterCurve);
|
||||
int count = _emitterCurve ? file.Emitters.Length : file.Particles.Length;
|
||||
if (count == 0)
|
||||
return;
|
||||
_particleIndex = EditorGUILayout.IntSlider("Resource index", _particleIndex, 0, count - 1);
|
||||
string[] names = _emitterCurve ? new[] { "Direction", "RandomVelocity", "Emission", "Life" } : new[] { "Size", "Rotation", "Alpha", "Color" };
|
||||
_curveIndex = EditorGUILayout.Popup("Curve", Mathf.Clamp(_curveIndex, 0, names.Length - 1), names);
|
||||
string name = names[_curveIndex];
|
||||
ParticleCurve source = OriginalEffectOverrides.FindCurve(file, _emitterCurve, _particleIndex, name);
|
||||
var entry = _edits.ParticleCurves.Find(c => string.Equals(c.File, path, StringComparison.OrdinalIgnoreCase)
|
||||
&& c.Emitter == _emitterCurve && c.Index == _particleIndex && c.Parameter == name);
|
||||
bool validEntry = entry == null || entry.Channels != null && entry.Channels.Length == source.Channels && entry.Channels.All(c => c != null);
|
||||
if (!validEntry)
|
||||
EditorGUILayout.HelpBox("This curve override has invalid channels. Restore the original curve to repair it.", MessageType.Warning);
|
||||
for (int channel = 0; channel < source.Channels; channel++)
|
||||
{
|
||||
if (!validEntry)
|
||||
break;
|
||||
AnimationCurve curve = entry != null ? CopyCurve(entry.Channels[channel]) : SampleCurve(source, channel);
|
||||
EditorGUI.BeginChangeCheck();
|
||||
AnimationCurve changed = EditorGUILayout.CurveField($"Channel {channel}", curve);
|
||||
if (EditorGUI.EndChangeCheck())
|
||||
{
|
||||
Undo.RecordObject(_edits, "Edit particle curve");
|
||||
if (entry == null)
|
||||
{
|
||||
entry = new OriginalParticleCurveOverride
|
||||
{
|
||||
File = path,
|
||||
Parameter = name,
|
||||
Index = _particleIndex,
|
||||
Emitter = _emitterCurve,
|
||||
Channels = Enumerable.Range(0, source.Channels).Select(c => SampleCurve(source, c)).ToArray()
|
||||
};
|
||||
_edits.ParticleCurves.Add(entry);
|
||||
}
|
||||
entry.Channels[channel] = CopyCurve(changed);
|
||||
MarkChanged();
|
||||
float time = _time;
|
||||
Restart();
|
||||
Seek(time);
|
||||
}
|
||||
}
|
||||
EditorGUILayout.LabelField(entry == null ? "Original sampled curve (unchanged)" : "Unity curve override for this particle resource", EditorStyles.wordWrappedMiniLabel);
|
||||
if (entry != null && GUILayout.Button("Restore original particle curve"))
|
||||
{
|
||||
Undo.RecordObject(_edits, "Restore particle curve");
|
||||
_edits.ParticleCurves.Remove(entry);
|
||||
MarkChanged();
|
||||
float time = _time;
|
||||
Restart();
|
||||
Seek(time);
|
||||
}
|
||||
}
|
||||
|
||||
private static AnimationCurve CopyCurve(AnimationCurve curve) =>
|
||||
new(curve.keys)
|
||||
{
|
||||
preWrapMode = curve.preWrapMode,
|
||||
postWrapMode = curve.postWrapMode
|
||||
};
|
||||
|
||||
private static AnimationCurve SampleCurve(ParticleCurve source, int channel)
|
||||
{
|
||||
var curve = new AnimationCurve(Enumerable.Range(0, 101).Select(i => new Keyframe(i / 100f, source.Evaluate(i / 100f, channel))).ToArray());
|
||||
for (int i = 0; i < curve.length; i++)
|
||||
{
|
||||
AnimationUtility.SetKeyLeftTangentMode(curve, i, AnimationUtility.TangentMode.Linear);
|
||||
AnimationUtility.SetKeyRightTangentMode(curve, i, AnimationUtility.TangentMode.Linear);
|
||||
}
|
||||
return curve;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 28e20becd27fe4cc3b3151897935cd30
|
||||
@@ -1,61 +0,0 @@
|
||||
// ------------------------------------------------------------------------
|
||||
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
|
||||
// See LICENSE file in the project root for license information.
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
namespace Editor
|
||||
{
|
||||
using System;
|
||||
using System.Linq;
|
||||
using UnityEditor;
|
||||
using UnityEditor.Build;
|
||||
using UnityEditor.Build.Reporting;
|
||||
|
||||
internal sealed class PrivateAssetBuildGuard : IPreprocessBuildWithReport
|
||||
{
|
||||
private const string PrivateBuildVariable = "PAL3_ALLOW_PRIVATE_ASSETS";
|
||||
private const string StoryVfxPath = "/Resources/Prefabs/VFX/";
|
||||
private const string HovlStudioPath = "/Hovl Studio/";
|
||||
private const string RealToonPath = "/RealToon/";
|
||||
private const string LegacyToonMaterialsPath = "Assets/Resources/Materials/";
|
||||
private const string Pal3VfxReadme = "Assets/Resources/Prefabs/VFX/PAL3/README.txt";
|
||||
private const string Pal3AVfxReadme = "Assets/Resources/Prefabs/VFX/PAL3A/README.txt";
|
||||
|
||||
internal static bool PrivateBuildEnabled =>
|
||||
Environment.GetEnvironmentVariable(PrivateBuildVariable) == "1" &&
|
||||
string.IsNullOrEmpty(Environment.GetEnvironmentVariable("CI")) &&
|
||||
string.IsNullOrEmpty(Environment.GetEnvironmentVariable("GITHUB_ACTIONS"));
|
||||
|
||||
public int callbackOrder => int.MaxValue;
|
||||
|
||||
public void OnPreprocessBuild(BuildReport report) => Validate();
|
||||
|
||||
internal static void Validate()
|
||||
{
|
||||
if (PrivateBuildEnabled) return;
|
||||
|
||||
string privateAsset = AssetDatabase.GetAllAssetPaths().FirstOrDefault(IsPrivateAsset);
|
||||
if (privateAsset == null) return;
|
||||
|
||||
throw new BuildFailedException(
|
||||
$"Local optional VFX or legacy Toon assets are installed ({privateAsset}). " +
|
||||
"Use a clean checkout for public builds. " +
|
||||
$"For a private local build, launch Unity with {PrivateBuildVariable}=1.");
|
||||
}
|
||||
|
||||
private static bool IsPrivateAsset(string assetPath)
|
||||
{
|
||||
if (assetPath.IndexOf(HovlStudioPath, StringComparison.OrdinalIgnoreCase) < 0 &&
|
||||
assetPath.IndexOf(RealToonPath, StringComparison.OrdinalIgnoreCase) < 0 &&
|
||||
!assetPath.StartsWith(LegacyToonMaterialsPath, StringComparison.OrdinalIgnoreCase) &&
|
||||
assetPath.IndexOf(StoryVfxPath, StringComparison.OrdinalIgnoreCase) < 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return !assetPath.Equals(Pal3VfxReadme, StringComparison.OrdinalIgnoreCase) &&
|
||||
!assetPath.Equals(Pal3AVfxReadme, StringComparison.OrdinalIgnoreCase) &&
|
||||
!AssetDatabase.IsValidFolder(assetPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ac41b9b3ac5641d98126273f7efb452f
|
||||
@@ -131,15 +131,13 @@ namespace Editor
|
||||
|
||||
private static void BuildGame(Pal3BuildTarget buildTarget)
|
||||
{
|
||||
PrivateAssetBuildGuard.Validate();
|
||||
|
||||
BuildTargetGroup targetGroupBeforeBuild = EditorUserBuildSettings.selectedBuildTargetGroup;
|
||||
BuildTarget targetBeforeBuild = EditorUserBuildSettings.activeBuildTarget;
|
||||
|
||||
string buildOutputPath = EditorUtility.SaveFolderPanel("Choose Location of Built Game", "", "");
|
||||
if (string.IsNullOrWhiteSpace(buildOutputPath)) return;
|
||||
|
||||
string versionFolder = GetVersionFolderName(PrivateAssetBuildGuard.PrivateBuildEnabled);
|
||||
string versionFolder = GetVersionFolderName();
|
||||
buildOutputPath += $"{DirSeparator}{versionFolder}{DirSeparator}";
|
||||
|
||||
var buildConfigurations = new[]
|
||||
@@ -271,14 +269,14 @@ namespace Editor
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetVersionFolderName(bool privateBuild)
|
||||
private static string GetVersionFolderName()
|
||||
{
|
||||
return PlayerSettings.bundleVersion + (privateBuild ? "-Private" : "");
|
||||
return PlayerSettings.bundleVersion;
|
||||
}
|
||||
|
||||
private static void ZipReleaseFiles()
|
||||
{
|
||||
string versionFolder = GetVersionFolderName(PrivateAssetBuildGuard.PrivateBuildEnabled);
|
||||
string versionFolder = GetVersionFolderName();
|
||||
string buildOutputPath = EditorUtility.SaveFolderPanel("Choose Location of Built Game",
|
||||
versionFolder, versionFolder);
|
||||
if (string.IsNullOrWhiteSpace(buildOutputPath)) return;
|
||||
@@ -289,12 +287,10 @@ namespace Editor
|
||||
{
|
||||
string selectedFolder = Path.GetFileName(buildOutputPath.TrimEnd(
|
||||
Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
|
||||
bool privateBuild = selectedFolder == GetVersionFolderName(true);
|
||||
if (!privateBuild && selectedFolder != GetVersionFolderName(false))
|
||||
if (selectedFolder != GetVersionFolderName())
|
||||
{
|
||||
Debug.LogError($"Invalid build output path: {buildOutputPath}. " +
|
||||
$"Please choose the current release build folder \"{GetVersionFolderName(false)}\" " +
|
||||
$"or \"{GetVersionFolderName(true)}\".");
|
||||
$"Please choose the current release build folder \"{GetVersionFolderName()}\".");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -313,7 +309,7 @@ namespace Editor
|
||||
foreach ((string folderPath, Pal3BuildTarget target) in buildTargets)
|
||||
{
|
||||
string fullPath = $"{buildOutputPath}{DirSeparator}{folderPath}";
|
||||
string zipFileName = $"{GameConstants.AppName}_v{GetVersionFolderName(privateBuild)}_{target.ToString()}.zip";
|
||||
string zipFileName = $"{GameConstants.AppName}_v{GetVersionFolderName()}_{target.ToString()}.zip";
|
||||
string zipFilePath = $"{releaseDirPath}{DirSeparator}{zipFileName}";
|
||||
|
||||
if (File.Exists(fullPath) || Directory.Exists(fullPath))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0b0b27c9e5e4d2e4fbc9b6584f828f7b
|
||||
guid: 7f8f503fe8584c3e887350c2988f8a22
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
@@ -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
|
||||
@@ -11,8 +11,16 @@ namespace Engine.Extensions
|
||||
{
|
||||
if (obj != null)
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
// Model renderers are also used in isolated editor preview scenes.
|
||||
if (!UnityEngine.Application.isPlaying)
|
||||
{
|
||||
UnityEngine.Object.DestroyImmediate(obj);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
UnityEngine.Object.Destroy(obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -61,65 +61,5 @@ namespace Pal3.Core.Contract.Constants
|
||||
"", 1f, 0.6f) },
|
||||
};
|
||||
#endif
|
||||
|
||||
#if PAL3
|
||||
// Effect group id to sfx mapping
|
||||
public static readonly Dictionary<int, string> EffectSfxInfo = new()
|
||||
{
|
||||
{ 251, "wd163" },
|
||||
{ 252, "wd160" },
|
||||
{ 254, "wd163" },
|
||||
{ 255, "wd155" },
|
||||
{ 256, "wd008" },
|
||||
{ 257, "wd001" },
|
||||
{ 261, "wd163" },
|
||||
{ 264, "wd160" },
|
||||
{ 266, "wd160" },
|
||||
{ 276, "wd150" },
|
||||
{ 278, "wd150" },
|
||||
{ 297, "wd141" },
|
||||
{ 341, "wd160" },
|
||||
{ 457, "wd141" },
|
||||
{ 458, "wd140" },
|
||||
};
|
||||
#elif PAL3A
|
||||
public static readonly Dictionary<int, string> EffectSfxInfo = new()
|
||||
{
|
||||
{ 91, "WD156" },
|
||||
{ 170, "WD155" },
|
||||
{ 171, "WD163" },
|
||||
{ 172, "WD189" },
|
||||
{ 173, "WD189" },
|
||||
{ 174, "WD308" },
|
||||
{ 175, "WD051" },
|
||||
{ 176, "WD051" },
|
||||
{ 177, "WD159" },
|
||||
{ 178, "WD032" },
|
||||
{ 179, "WD497" },
|
||||
{ 181, "WD018" },
|
||||
{ 182, "WD018" },
|
||||
{ 189, "WD035" },
|
||||
{ 198, "WD018" },
|
||||
{ 209, "WD309" },
|
||||
{ 211, "WD002" },
|
||||
{ 230, "WD342" },
|
||||
{ 254, "WD163" },
|
||||
{ 257, "WD008" },
|
||||
{ 258, "WD165" },
|
||||
{ 259, "WD163" },
|
||||
{ 281, "WD159" },
|
||||
{ 283, "WD018" },
|
||||
{ 285, "WD422" },
|
||||
{ 290, "WD418" },
|
||||
{ 299, "WD150" },
|
||||
{ 322, "WD163" },
|
||||
{ 323, "WD189" },
|
||||
{ 328, "WD532" },
|
||||
{ 388, "WD165" },
|
||||
{ 389, "WD165" },
|
||||
{ 397, "WD459" },
|
||||
{ 408, "WD459" },
|
||||
};
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
* @note Uses unsafe/fixed pointer contexts internally
|
||||
* @liscence Bound by same liscence as minilzo as below, see file COPYING
|
||||
*/
|
||||
|
||||
/* Based on minilzo.c -- mini subset of the LZO real-time data compression library
|
||||
|
||||
This file is part of the LZO real-time data compression library.
|
||||
@@ -58,9 +57,16 @@ namespace Pal3.Core.DataReader.Cpk.Lzo
|
||||
{
|
||||
private const uint M2_MAX_OFFSET = 0x0800;
|
||||
|
||||
public static unsafe void Decompress(Span<byte> src, byte[] dst)
|
||||
public static void Decompress(Span<byte> src, byte[] dst) => DecompressInternal(src, dst, false);
|
||||
|
||||
// Some PAL3 flexeff files retain a complete LZO stream followed by unused
|
||||
// bytes in a fixed-size file. Keep ordinary CPK decompression strict.
|
||||
public static int DecompressPrefix(Span<byte> src, byte[] dst) => DecompressInternal(src, dst, true);
|
||||
|
||||
private static unsafe int DecompressInternal(Span<byte> src, byte[] dst, bool allowTrailingBytes)
|
||||
{
|
||||
if (src.Length < 3) throw new OverflowException("Input Overrun");
|
||||
if (src.Length < 3)
|
||||
throw new OverflowException("Input Overrun");
|
||||
uint t = 0;
|
||||
fixed (byte* input = src, output = dst)
|
||||
{
|
||||
@@ -276,7 +282,7 @@ namespace Pal3.Core.DataReader.Cpk.Lzo
|
||||
} while (--t > 0);
|
||||
}
|
||||
}
|
||||
else if(!eof_found && !match_done)
|
||||
else if (!eof_found && !match_done)
|
||||
{
|
||||
copy_match = false;
|
||||
|
||||
@@ -320,13 +326,15 @@ namespace Pal3.Core.DataReader.Cpk.Lzo
|
||||
throw new OverflowException("EOF Marker Not Found");
|
||||
else
|
||||
{
|
||||
if (op != op_end) throw new OverflowException("Output Length Mismatch");
|
||||
if (op != op_end)
|
||||
throw new OverflowException("Output Length Mismatch");
|
||||
//Debug.Assert(t == 1);
|
||||
if (ip > ip_end)
|
||||
throw new OverflowException("Input Overrun");
|
||||
else if (ip < ip_end)
|
||||
else if (ip < ip_end && !allowTrailingBytes)
|
||||
throw new OverflowException("Input Not Consumed");
|
||||
}
|
||||
return checked((int)(ip - input));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ namespace Pal3.Core.DataReader.Data
|
||||
//using System.Runtime.InteropServices;
|
||||
|
||||
//[StructLayout(LayoutKind.Explicit)]
|
||||
[System.Serializable]
|
||||
public struct EffectDefinition
|
||||
{
|
||||
//[FieldOffset(0)]
|
||||
@@ -55,7 +56,7 @@ namespace Pal3.Core.DataReader.Data
|
||||
public float InitAngle;
|
||||
|
||||
//[FieldOffset(200)]
|
||||
public int InitSize;
|
||||
public float InitSize;
|
||||
|
||||
//[FieldOffset(204)]
|
||||
public uint InitColor;
|
||||
@@ -124,11 +125,27 @@ namespace Pal3.Core.DataReader.Data
|
||||
|
||||
public sealed class EffectDefinitionFile
|
||||
{
|
||||
public EffectDefinitionFile(EffectDefinition[] effectDefinitions)
|
||||
private readonly System.Collections.Generic.Dictionary<uint, EffectDefinition> _types = new();
|
||||
|
||||
public EffectDefinitionFile(EffectDefinition[] effectDefinitions, EffectGroup[] groups = null)
|
||||
{
|
||||
EffectDefinitions = effectDefinitions;
|
||||
Groups = groups ?? System.Array.Empty<EffectGroup>();
|
||||
foreach (EffectDefinition definition in effectDefinitions)
|
||||
if (definition.IsValid && !_types.ContainsKey(definition.TypeNameCrc))
|
||||
_types.Add(definition.TypeNameCrc, definition);
|
||||
}
|
||||
|
||||
public EffectDefinition[] EffectDefinitions { get; }
|
||||
public EffectDefinition[] EffectDefinitions
|
||||
{
|
||||
get;
|
||||
}
|
||||
|
||||
public EffectGroup[] Groups
|
||||
{
|
||||
get;
|
||||
}
|
||||
|
||||
public bool TryGetType(uint crc, out EffectDefinition definition) => _types.TryGetValue(crc, out definition);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,22 +5,142 @@
|
||||
|
||||
namespace Pal3.Core.DataReader.Data
|
||||
{
|
||||
using System;
|
||||
|
||||
public sealed class EffectDefinitionFileReader : IFileReader<EffectDefinitionFile>
|
||||
{
|
||||
private const int NUM_OF_EFFECTS = 1324;
|
||||
public const int Pal3Size = 1324 * 280 + 560 * 15940;
|
||||
public const int Pal3ASize = 2048 * 280 + 1024 * 15940;
|
||||
|
||||
public EffectDefinitionFile Read(IBinaryReader reader, int codepage)
|
||||
{
|
||||
EffectDefinition[] effectDefinitions = new EffectDefinition[NUM_OF_EFFECTS];
|
||||
|
||||
for (int i = 0; i < NUM_OF_EFFECTS; i++)
|
||||
byte[] bytes = reader.ReadExactly(checked((int)(reader.Length - reader.Position)));
|
||||
// Validate the layout before accepting an unwrapped file. The shipped
|
||||
// PAL3 sample is a padded LZO stream with the same length as the table.
|
||||
if (bytes.Length == Pal3Size || bytes.Length == Pal3ASize)
|
||||
{
|
||||
effectDefinitions[i] = ReadEffectDefinition(reader, codepage);
|
||||
}
|
||||
try
|
||||
{
|
||||
return ReadPayload(bytes, codepage);
|
||||
}
|
||||
catch (System.IO.InvalidDataException)
|
||||
{
|
||||
|
||||
return new EffectDefinitionFile(effectDefinitions);
|
||||
}
|
||||
var decoded = new byte[bytes.Length];
|
||||
Cpk.Lzo.MiniLzo.DecompressPrefix(bytes, decoded);
|
||||
return ReadPayload(decoded, codepage);
|
||||
}
|
||||
if (bytes.Length >= 7)
|
||||
{
|
||||
int size = bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24;
|
||||
if (size == Pal3Size || size == Pal3ASize)
|
||||
{
|
||||
var decoded = new byte[size];
|
||||
Cpk.Lzo.MiniLzo.Decompress(bytes.AsSpan(4), decoded);
|
||||
return ReadPayload(decoded, codepage);
|
||||
}
|
||||
}
|
||||
throw new System.IO.InvalidDataException("Unrecognized flexeff table layout or compression wrapper");
|
||||
}
|
||||
|
||||
private EffectDefinitionFile ReadPayload(byte[] bytes, int codepage)
|
||||
{
|
||||
int typeCount = bytes.Length == Pal3Size ? 1324 : 2048;
|
||||
int groupCount = bytes.Length == Pal3Size ? 560 : 1024;
|
||||
using IBinaryReader reader = new SafeBinaryReader(bytes);
|
||||
var definitions = new EffectDefinition[typeCount];
|
||||
for (int i = 0; i < typeCount; i++)
|
||||
{
|
||||
// Invalid slots may contain uninitialized native bytes.
|
||||
long offset = reader.Position;
|
||||
reader.Seek(offset + 212, System.IO.SeekOrigin.Begin);
|
||||
byte valid = reader.ReadByte();
|
||||
if (valid > 1)
|
||||
throw new System.IO.InvalidDataException($"Invalid effect type flag at {i}");
|
||||
reader.Seek(offset, System.IO.SeekOrigin.Begin);
|
||||
definitions[i] = ReadEffectDefinition(reader, codepage);
|
||||
if (valid == 1 && (float.IsNaN(definitions[i].InitSize) || float.IsInfinity(definitions[i].InitSize)))
|
||||
throw new System.IO.InvalidDataException($"Invalid effect size at {i}");
|
||||
}
|
||||
var groups = new EffectGroup[groupCount];
|
||||
for (int g = 0; g < groupCount; g++)
|
||||
{
|
||||
int count = reader.ReadInt32();
|
||||
if (count < 0 || count > 16)
|
||||
throw new System.IO.InvalidDataException($"Invalid effect group size at {g}");
|
||||
uint[] crcs = reader.ReadUInt32s(16);
|
||||
var objects = new EffectGroupObject[count];
|
||||
for (int o = 0; o < 16; o++)
|
||||
{
|
||||
var tasks = new System.Collections.Generic.List<EffectTask>();
|
||||
for (int t = 0; t < 8; t++)
|
||||
{
|
||||
if (o >= count)
|
||||
{
|
||||
reader.Seek(124, System.IO.SeekOrigin.Current);
|
||||
continue;
|
||||
}
|
||||
EffectTask task = ReadTask(reader);
|
||||
if (task.IsValid)
|
||||
tasks.Add(task);
|
||||
}
|
||||
if (o < count)
|
||||
objects[o] = new EffectGroupObject { TypeCrc = crcs[o], Tasks = tasks.ToArray() };
|
||||
}
|
||||
groups[g] = new EffectGroup { Objects = objects };
|
||||
}
|
||||
var file = new EffectDefinitionFile(definitions, groups);
|
||||
for (int g = 0; g < groups.Length; g++)
|
||||
foreach (EffectGroupObject obj in groups[g].Objects)
|
||||
if (!file.TryGetType(obj.TypeCrc, out _))
|
||||
throw new System.IO.InvalidDataException($"Group {g} references missing effect type {obj.TypeCrc:X8}");
|
||||
return file;
|
||||
}
|
||||
|
||||
private static EffectTask ReadTask(IBinaryReader reader)
|
||||
{
|
||||
var task = new EffectTask
|
||||
{
|
||||
XStretchSpeed = reader.ReadSingle(),
|
||||
SpeedX = reader.ReadSingle(),
|
||||
SpeedY = reader.ReadSingle(),
|
||||
SpeedZ = reader.ReadSingle(),
|
||||
SpeedRot = reader.ReadSingle(),
|
||||
CircleAxisX = reader.ReadSingle(),
|
||||
CircleAxisY = reader.ReadSingle(),
|
||||
CircleAxisZ = reader.ReadSingle(),
|
||||
CircleRadius = reader.ReadSingle(),
|
||||
CircleSpeed = reader.ReadSingle(),
|
||||
RotAxisX = reader.ReadSingle(),
|
||||
RotAxisY = reader.ReadSingle(),
|
||||
RotAxisZ = reader.ReadSingle(),
|
||||
RotSpeed = reader.ReadSingle(),
|
||||
SpeedAlpha = reader.ReadSingle(),
|
||||
SpeedRed = reader.ReadSingle(),
|
||||
SpeedGreen = reader.ReadSingle(),
|
||||
SpeedBlue = reader.ReadSingle(),
|
||||
StartTime = reader.ReadSingle(),
|
||||
Duration = reader.ReadSingle(),
|
||||
RequireLoops = reader.ReadInt32(),
|
||||
CreateTimeSlot = reader.ReadSingle(),
|
||||
};
|
||||
byte valid = reader.ReadByte();
|
||||
if (valid > 1)
|
||||
throw new System.IO.InvalidDataException("Invalid task validity flag");
|
||||
task.IsValid = valid == 1;
|
||||
task.CreateNew = reader.ReadBoolean();
|
||||
task.ModifyLast = reader.ReadBoolean();
|
||||
reader.ReadByte(); // native 4-byte alignment
|
||||
task.YStretchSpeed = reader.ReadSingle();
|
||||
reader.Seek(28, System.IO.SeekOrigin.Current); // reserved, not active parameters
|
||||
if (task.IsValid && (!Finite(task.StartTime) || !Finite(task.Duration) || task.Duration < 0))
|
||||
throw new System.IO.InvalidDataException("Invalid effect task timing");
|
||||
return task;
|
||||
}
|
||||
|
||||
private static bool Finite(float value) => !float.IsNaN(value) && !float.IsInfinity(value);
|
||||
|
||||
private EffectDefinition ReadEffectDefinition(IBinaryReader reader, int codepage)
|
||||
{
|
||||
EffectDefinition effectDefinition = new()
|
||||
@@ -55,7 +175,7 @@ namespace Pal3.Core.DataReader.Data
|
||||
effectDefinition.InitAngle = unionFloat;
|
||||
}
|
||||
|
||||
effectDefinition.InitSize = reader.ReadInt32();
|
||||
effectDefinition.InitSize = reader.ReadSingle();
|
||||
effectDefinition.InitColor = reader.ReadUInt32();
|
||||
effectDefinition.MaxQuadCount = reader.ReadInt32();
|
||||
|
||||
@@ -90,4 +210,4 @@ namespace Pal3.Core.DataReader.Data
|
||||
return effectDefinition;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
// ------------------------------------------------------------------------
|
||||
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
|
||||
// See LICENSE file in the project root for license information.
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
namespace Pal3.Core.DataReader.Data
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Cpk;
|
||||
using Primitives;
|
||||
|
||||
// The names describe the quad interpretation of the original unions.
|
||||
// Callback/audio/model adapters interpret these same fields by class.
|
||||
[Serializable]
|
||||
public sealed class EffectTask
|
||||
{
|
||||
public float XStretchSpeed, SpeedX, SpeedY, SpeedZ, SpeedRot;
|
||||
public float CircleAxisX, CircleAxisY, CircleAxisZ, CircleRadius, CircleSpeed;
|
||||
public float RotAxisX, RotAxisY, RotAxisZ, RotSpeed;
|
||||
public float SpeedAlpha, SpeedRed, SpeedGreen, SpeedBlue, StartTime, Duration;
|
||||
public int RequireLoops;
|
||||
public float CreateTimeSlot;
|
||||
public bool IsValid, CreateNew, ModifyLast;
|
||||
public float YStretchSpeed;
|
||||
|
||||
public GameBoxVector3 Speed => new(SpeedX, SpeedY, SpeedZ);
|
||||
public GameBoxVector3 CircleAxis => new(CircleAxisX, CircleAxisY, CircleAxisZ);
|
||||
|
||||
public IEnumerable<(int groupId, GameBoxVector3 position)> Callbacks()
|
||||
{
|
||||
if (XStretchSpeed != 0)
|
||||
yield return ((int)MathF.Round(XStretchSpeed), new(SpeedX, SpeedY, SpeedZ));
|
||||
if (CircleRadius != 0)
|
||||
yield return ((int)MathF.Round(CircleRadius), new(RotAxisX, RotAxisY, RotAxisZ));
|
||||
if (CircleAxisX != 0)
|
||||
yield return ((int)MathF.Round(CircleAxisX), new(CircleAxisY, CircleAxisZ, CircleSpeed));
|
||||
if (SpeedAlpha != 0)
|
||||
yield return ((int)MathF.Round(SpeedAlpha), new(SpeedRed, SpeedGreen, SpeedBlue));
|
||||
}
|
||||
|
||||
public IEnumerable<(int index, float delay)> Sounds()
|
||||
{
|
||||
if (XStretchSpeed != 0)
|
||||
yield return ((int)MathF.Round(XStretchSpeed), SpeedX);
|
||||
if (SpeedY != 0)
|
||||
yield return ((int)MathF.Round(SpeedY), SpeedZ);
|
||||
if (CircleRadius != 0)
|
||||
yield return ((int)MathF.Round(CircleRadius), RotAxisX);
|
||||
if (RotAxisY != 0)
|
||||
yield return ((int)MathF.Round(RotAxisY), RotAxisZ);
|
||||
}
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class EffectGroupObject
|
||||
{
|
||||
public uint TypeCrc;
|
||||
public EffectTask[] Tasks = Array.Empty<EffectTask>();
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class EffectGroup
|
||||
{
|
||||
public EffectGroupObject[] Objects = Array.Empty<EffectGroupObject>();
|
||||
}
|
||||
|
||||
public static class EffectClass
|
||||
{
|
||||
private static readonly Dictionary<uint, string> Names = CreateNames();
|
||||
|
||||
private static Dictionary<uint, string> CreateNames()
|
||||
{
|
||||
var hash = new Crc32Hash();
|
||||
hash.Init();
|
||||
var result = new Dictionary<uint, string>();
|
||||
foreach (string name in new[] { "quad", "particle", "cylinder", "model", "callback", "audio",
|
||||
"meteor", "shock", "grid", "explosive", "action", "camera", "time", "bink", "quake", "S-Particle" })
|
||||
result.Add(hash.Compute(name, 936), name);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static string Name(uint crc) => Names.TryGetValue(crc, out string name) ? name : $"unknown:{crc:X8}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9fd0064acbd0242f981e846ddb645825
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c2f352a62352f4c2b8747dd5dd7168ae
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,88 @@
|
||||
// ------------------------------------------------------------------------
|
||||
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
|
||||
// See LICENSE file in the project root for license information.
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
namespace Pal3.Core.DataReader.Par
|
||||
{
|
||||
using System;
|
||||
using Primitives;
|
||||
|
||||
public sealed class ParticleCurve
|
||||
{
|
||||
public int Channels;
|
||||
public string Name;
|
||||
public GameBoxVector3[][] Samples;
|
||||
|
||||
public Func<float, int, float> OverrideEvaluation
|
||||
{
|
||||
get; set;
|
||||
}
|
||||
|
||||
public float Evaluate(float time, int channel = 0)
|
||||
{
|
||||
if (OverrideEvaluation != null)
|
||||
return OverrideEvaluation(time, channel);
|
||||
if (channel < 0 || channel >= Channels)
|
||||
return 0;
|
||||
int lo = 0, hi = 100;
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
int mid = (hi + lo) / 2;
|
||||
if (Samples[0][mid].X <= time)
|
||||
lo = mid;
|
||||
else
|
||||
hi = mid;
|
||||
}
|
||||
for (int i = lo; i < hi; i++)
|
||||
{
|
||||
if (Samples[0][i].X > time || Samples[0][i + 1].X < time)
|
||||
continue;
|
||||
GameBoxVector3 a = Samples[channel][i], b = Samples[channel][i + 1];
|
||||
return b.X == a.X ? a.Y : a.Y + (b.Y - a.Y) * ((time - a.X) / (b.X - a.X));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ParticleDescription
|
||||
{
|
||||
public string Name, Texture;
|
||||
public float Gravity, NoResistanceSpeed, Resistance;
|
||||
public int VelocityResistancePower, SizeResistancePower, TextureSize, AnimationType, Fps;
|
||||
public bool RandomFirstFrame, RandomRotationDirection, MirrorX, MirrorY;
|
||||
public int RotationStart, RotationEnd, Rows, Columns, BlendMode;
|
||||
public ParticleCurve Size, Rotation, Alpha, Color;
|
||||
}
|
||||
|
||||
public sealed class ParticleEmitter
|
||||
{
|
||||
public string Name, ShapePath;
|
||||
public GameBoxVector3 Position, Scope, BoxMin, BoxMax;
|
||||
public int Shape;
|
||||
public float SpeedMultiplier, CycleMin, CycleMax, Hotspot, Falloff;
|
||||
public bool Loop;
|
||||
public ParticleCurve Direction, RandomVelocity, Emission, Life, Size, Rotation;
|
||||
}
|
||||
|
||||
public sealed class ParticleController
|
||||
{
|
||||
public string Name;
|
||||
public int ParticleIndex, EmitterIndex, Capacity;
|
||||
}
|
||||
|
||||
public sealed class ParticleFile
|
||||
{
|
||||
public uint Version;
|
||||
public int Capacity, Space, Overflow;
|
||||
public float Scale;
|
||||
public ParticleDescription[] Particles;
|
||||
public ParticleEmitter[] Emitters;
|
||||
public ParticleController[] Controllers;
|
||||
}
|
||||
|
||||
public sealed class ParticleShapeFile
|
||||
{
|
||||
public GameBoxVector3[] Points;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 30b0fbf09f821494eb895c502aa5cdcb
|
||||
@@ -0,0 +1,160 @@
|
||||
// ------------------------------------------------------------------------
|
||||
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
|
||||
// See LICENSE file in the project root for license information.
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
namespace Pal3.Core.DataReader.Par
|
||||
{
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
public sealed class ParticleFileReader : IFileReader<ParticleFile>
|
||||
{
|
||||
public ParticleFile Read(IBinaryReader r, int codepage)
|
||||
{
|
||||
if (r.ReadString(6) != "sgpar\0")
|
||||
throw new InvalidDataException("Not an sgpar particle file (SPar is not supported)");
|
||||
uint version = r.ReadUInt32();
|
||||
if (version != 0x10000 && version != 0x10001)
|
||||
throw new InvalidDataException($"Unsupported sgpar version {version:X}");
|
||||
var file = new ParticleFile
|
||||
{
|
||||
Version = version,
|
||||
Capacity = Count(r, 65536),
|
||||
Space = r.ReadInt32(),
|
||||
Overflow = r.ReadInt32(),
|
||||
Scale = version > 0x10000 ? r.ReadSingle() : 1f
|
||||
};
|
||||
if (file.Space < 0 || file.Space > 1 || file.Overflow < 0 || file.Overflow > 2 || !Finite(file.Scale) || file.Scale <= 0)
|
||||
throw new InvalidDataException("Invalid sgpar scene parameters");
|
||||
int np = Count(r, 64), ne = Count(r, 64), nc = Count(r, 64);
|
||||
file.Particles = new ParticleDescription[np];
|
||||
file.Emitters = new ParticleEmitter[ne];
|
||||
file.Controllers = new ParticleController[nc];
|
||||
for (int i = 0; i < np; i++)
|
||||
file.Particles[i] = ReadParticle(r, codepage);
|
||||
for (int i = 0; i < ne; i++)
|
||||
file.Emitters[i] = ReadEmitter(r, codepage, version);
|
||||
for (int i = 0; i < nc; i++)
|
||||
{
|
||||
var c = new ParticleController
|
||||
{
|
||||
Name = r.ReadString(64, codepage),
|
||||
ParticleIndex = r.ReadInt32(),
|
||||
EmitterIndex = r.ReadInt32(),
|
||||
Capacity = Count(r, 65536)
|
||||
};
|
||||
if (c.ParticleIndex < 0 || c.ParticleIndex >= np || c.EmitterIndex < 0 || c.EmitterIndex >= ne)
|
||||
throw new InvalidDataException("Invalid sgpar controller reference");
|
||||
file.Controllers[i] = c;
|
||||
}
|
||||
if (r.Position != r.Length)
|
||||
throw new InvalidDataException("Unexpected sgpar trailing data");
|
||||
return file;
|
||||
}
|
||||
|
||||
private static ParticleDescription ReadParticle(IBinaryReader r, int cp)
|
||||
{
|
||||
var p = new ParticleDescription { Name = r.ReadString(32, cp) };
|
||||
r.ReadInt32(); // native BOOL lighting (unused by original renderer)
|
||||
p.Gravity = r.ReadSingle();
|
||||
p.NoResistanceSpeed = r.ReadSingle();
|
||||
p.VelocityResistancePower = r.ReadInt32();
|
||||
p.SizeResistancePower = r.ReadInt32();
|
||||
p.Resistance = r.ReadSingle();
|
||||
p.Texture = r.ReadString(256, cp);
|
||||
p.TextureSize = r.ReadInt32();
|
||||
p.AnimationType = r.ReadInt32();
|
||||
p.Fps = r.ReadInt32();
|
||||
p.RandomFirstFrame = r.ReadInt32() != 0;
|
||||
p.RotationStart = r.ReadInt32();
|
||||
p.RotationEnd = r.ReadInt32();
|
||||
p.RandomRotationDirection = r.ReadInt32() != 0;
|
||||
p.MirrorX = r.ReadInt32() != 0;
|
||||
p.MirrorY = r.ReadInt32() != 0;
|
||||
p.Rows = r.ReadInt32();
|
||||
p.Columns = r.ReadInt32();
|
||||
p.BlendMode = r.ReadInt32();
|
||||
if (p.Rows < 1 || p.Columns < 1 || p.Rows > 256 || p.Columns > 256)
|
||||
throw new InvalidDataException("Invalid particle atlas");
|
||||
p.Size = ReadCurve(r, cp);
|
||||
p.Rotation = ReadCurve(r, cp);
|
||||
p.Alpha = ReadCurve(r, cp);
|
||||
p.Color = ReadCurve(r, cp);
|
||||
return p;
|
||||
}
|
||||
|
||||
private static ParticleEmitter ReadEmitter(IBinaryReader r, int cp, uint version)
|
||||
{
|
||||
var e = new ParticleEmitter { Name = r.ReadString(64, cp), Position = r.ReadGameBoxVector3(), Scope = r.ReadGameBoxVector3(), Shape = r.ReadInt32() };
|
||||
e.ShapePath = version > 0x10000 ? r.ReadString(64, cp) : "";
|
||||
e.SpeedMultiplier = version > 0x10000 ? r.ReadSingle() : 1f;
|
||||
e.CycleMin = r.ReadSingle();
|
||||
e.CycleMax = r.ReadSingle();
|
||||
e.Loop = r.ReadInt32() != 0;
|
||||
r.ReadInt32(); // lighton
|
||||
e.Hotspot = r.ReadSingle();
|
||||
e.Falloff = r.ReadSingle();
|
||||
e.BoxMin = r.ReadGameBoxVector3();
|
||||
e.BoxMax = r.ReadGameBoxVector3();
|
||||
if (e.Shape < 0 || e.Shape > 2)
|
||||
throw new InvalidDataException("Invalid sgpar emitter shape");
|
||||
e.Direction = ReadCurve(r, cp);
|
||||
e.RandomVelocity = ReadCurve(r, cp);
|
||||
e.Emission = ReadCurve(r, cp);
|
||||
e.Life = ReadCurve(r, cp);
|
||||
e.Size = ReadCurve(r, cp);
|
||||
e.Rotation = ReadCurve(r, cp);
|
||||
return e;
|
||||
}
|
||||
|
||||
private static ParticleCurve ReadCurve(IBinaryReader r, int cp)
|
||||
{
|
||||
int channels = Count(r, 3), points = Count(r, 20);
|
||||
var curve = new ParticleCurve { Channels = channels, Name = r.ReadString(64, cp), Samples = new Primitives.GameBoxVector3[3][] };
|
||||
r.ReadString(128, cp);
|
||||
r.ReadGameBoxVector3();
|
||||
r.ReadGameBoxVector3();
|
||||
r.Seek(2 * 3 * 20 * 12, SeekOrigin.Current); // editor and real control points; runtime uses stored samples
|
||||
for (int c = 0; c < 3; c++)
|
||||
curve.Samples[c] = r.ReadGameBoxVector3s(101);
|
||||
for (int c = 0; c < channels; c++)
|
||||
for (int i = 0; i < 101; i++)
|
||||
{
|
||||
var p = curve.Samples[c][i];
|
||||
// Shipped curves can double back in x. Preserve their original
|
||||
// sample order and lookup semantics instead of sorting them.
|
||||
if (!Finite(p.X) || !Finite(p.Y))
|
||||
throw new InvalidDataException($"Invalid particle curve {curve.Name} channel={c} sample={i} x={p.X} y={p.Y} previous={(i > 0 ? curve.Samples[c][i - 1].X : 0)}");
|
||||
}
|
||||
return curve;
|
||||
}
|
||||
|
||||
private static int Count(IBinaryReader r, int max)
|
||||
{
|
||||
int value = r.ReadInt32();
|
||||
if (value < 0 || value > max)
|
||||
throw new InvalidDataException("Invalid sgpar count");
|
||||
return value;
|
||||
}
|
||||
|
||||
private static bool Finite(float v) => !float.IsNaN(v) && !float.IsInfinity(v);
|
||||
}
|
||||
|
||||
public sealed class ParticleShapeFileReader : IFileReader<ParticleShapeFile>
|
||||
{
|
||||
public ParticleShapeFile Read(IBinaryReader r, int codepage)
|
||||
{
|
||||
if (r.ReadString(4) != "csf\0")
|
||||
throw new InvalidDataException("Invalid CSF header");
|
||||
r.ReadUInt32();
|
||||
int count = r.ReadInt32();
|
||||
if (count < 2 || count > 1000000 || count > (r.Length - r.Position) / 12)
|
||||
throw new InvalidDataException("Invalid CSF point count");
|
||||
var result = new ParticleShapeFile { Points = r.ReadGameBoxVector3s(count) };
|
||||
if (r.Position != r.Length)
|
||||
throw new InvalidDataException("Unexpected CSF trailing data");
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0c0f89a3d0f3c4df9864b29cbc004105
|
||||
@@ -0,0 +1,60 @@
|
||||
// ------------------------------------------------------------------------
|
||||
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
|
||||
// See LICENSE file in the project root for license information.
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
namespace Pal3.Core.DataReader.Par
|
||||
{
|
||||
using System;
|
||||
using Primitives;
|
||||
|
||||
[Serializable]
|
||||
public sealed class SparController
|
||||
{
|
||||
public int Kind;
|
||||
public float[] Parameters;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class SparKeyframe
|
||||
{
|
||||
public float Time;
|
||||
public GameBoxVector3 Position;
|
||||
public int EmissionMinimum, EmissionMaximum, Shape;
|
||||
public float[] ShapeParameters;
|
||||
public bool HasPath;
|
||||
public float PathRate;
|
||||
public GameBoxVector3[] PathPoints;
|
||||
public GameBoxVector3 VelocityMinimum, VelocityMaximum;
|
||||
public float RotationMinimum, RotationMaximum, SpinMinimum, SpinMaximum;
|
||||
public GameBoxVector3 ColorMinimum, ColorMaximum;
|
||||
public float AlphaMinimum, AlphaMaximum, LifeMinimum, LifeMaximum, SizeMinimum, SizeMaximum;
|
||||
public int FrameMinimum, FrameMaximum;
|
||||
public SparController[] Controllers;
|
||||
public float[] Reserved;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class SparGroup
|
||||
{
|
||||
public string Name, Texture;
|
||||
public int Capacity, VertexCapacity, Mode;
|
||||
public bool Loop;
|
||||
// Rebuilt by the binary reader; jagged arrays are not Unity-serializable.
|
||||
[NonSerialized]
|
||||
public float[][] TextureFrames;
|
||||
public SparKeyframe[] Keyframes;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class SparFile
|
||||
{
|
||||
public float Version;
|
||||
public SparGroup[] Groups;
|
||||
public int Shader;
|
||||
public float[] ShaderParameters;
|
||||
// Some exported files contain an editor tail. The original loader closes
|
||||
// the file after the shader parameters and never consumes this tail.
|
||||
public int UnusedByteCount;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f413782ba81242aea2d6d1c011781e39
|
||||
@@ -0,0 +1,132 @@
|
||||
// ------------------------------------------------------------------------
|
||||
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
|
||||
// See LICENSE file in the project root for license information.
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
namespace Pal3.Core.DataReader.Par
|
||||
{
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
// PAL3A.exe loader 0x4c65a3. This is independent of the sgpar format.
|
||||
public sealed class SparFileReader : IFileReader<SparFile>
|
||||
{
|
||||
public SparFile Read(IBinaryReader r, int codepage)
|
||||
{
|
||||
byte[] header = r.ReadExactly(264);
|
||||
using IBinaryReader h = new SafeBinaryReader(header);
|
||||
float version = h.ReadSingle();
|
||||
int count = Count(h, 128);
|
||||
if (version != 1 || h.ReadString(40) != "__PARTICLE_EFFECT(Softstar_Ltd)_EXPORT__")
|
||||
throw new InvalidDataException("Unsupported SPar export header");
|
||||
var file = new SparFile { Version = version, Groups = new SparGroup[count] };
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
using IBinaryReader g = new SafeBinaryReader(r.ReadExactly(544));
|
||||
g.ReadUInt32(); // native editor/runtime pointer, not a file offset
|
||||
var group = new SparGroup { Capacity = Count(g, 65536), VertexCapacity = Count(g, 393216), Mode = g.ReadInt32(), Loop = g.ReadInt32() != 0 };
|
||||
int frames = Count(g, 4096), keys = Count(g, 4096);
|
||||
group.Name = g.ReadString(256, codepage);
|
||||
group.Texture = g.ReadString(260, codepage);
|
||||
group.TextureFrames = new float[frames][];
|
||||
for (int frame = 0; frame < frames; frame++)
|
||||
group.TextureFrames[frame] = Floats(r, 4);
|
||||
group.Keyframes = new SparKeyframe[keys];
|
||||
for (int key = 0; key < keys; key++)
|
||||
group.Keyframes[key] = Keyframe(r);
|
||||
file.Groups[i] = group;
|
||||
}
|
||||
Require(r, 20);
|
||||
file.Shader = r.ReadInt32();
|
||||
file.ShaderParameters = Floats(r, 4);
|
||||
file.UnusedByteCount = checked((int)(r.Length - r.Position));
|
||||
return file;
|
||||
}
|
||||
|
||||
private static SparKeyframe Keyframe(IBinaryReader r)
|
||||
{
|
||||
Require(r, 28);
|
||||
var key = new SparKeyframe
|
||||
{
|
||||
Time = r.ReadSingle(),
|
||||
Position = r.ReadGameBoxVector3(),
|
||||
EmissionMinimum = r.ReadInt32(),
|
||||
EmissionMaximum = r.ReadInt32(),
|
||||
Shape = r.ReadInt32()
|
||||
};
|
||||
int values = key.Shape switch
|
||||
{
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
2 => 6,
|
||||
3 => checked(Count(r, 1000000) * 3),
|
||||
_ => throw new InvalidDataException($"Unknown SPar spawn shape {key.Shape}")
|
||||
};
|
||||
key.ShapeParameters = Floats(r, values);
|
||||
Require(r, 4);
|
||||
key.HasPath = r.ReadInt32() != 0;
|
||||
if (key.HasPath)
|
||||
{
|
||||
Require(r, 4);
|
||||
key.PathRate = r.ReadSingle();
|
||||
int count = Count(r, 1000000);
|
||||
Require(r, checked(count * 12));
|
||||
key.PathPoints = new Primitives.GameBoxVector3[count];
|
||||
for (int i = 0; i < count; i++)
|
||||
key.PathPoints[i] = r.ReadGameBoxVector3();
|
||||
}
|
||||
else
|
||||
key.PathPoints = Array.Empty<Primitives.GameBoxVector3>();
|
||||
Require(r, 96);
|
||||
key.VelocityMinimum = r.ReadGameBoxVector3();
|
||||
key.VelocityMaximum = r.ReadGameBoxVector3();
|
||||
key.RotationMinimum = r.ReadSingle();
|
||||
key.RotationMaximum = r.ReadSingle();
|
||||
key.SpinMinimum = r.ReadSingle();
|
||||
key.SpinMaximum = r.ReadSingle();
|
||||
key.ColorMinimum = r.ReadGameBoxVector3();
|
||||
key.ColorMaximum = r.ReadGameBoxVector3();
|
||||
key.AlphaMinimum = r.ReadSingle();
|
||||
key.AlphaMaximum = r.ReadSingle();
|
||||
key.LifeMinimum = r.ReadSingle();
|
||||
key.LifeMaximum = r.ReadSingle();
|
||||
key.SizeMinimum = r.ReadSingle();
|
||||
key.SizeMaximum = r.ReadSingle();
|
||||
key.FrameMinimum = r.ReadInt32();
|
||||
key.FrameMaximum = r.ReadInt32();
|
||||
int[][] parameters = { new[] { 0, 0, 3, 4, 0, 0, 0 }, new[] { 0, 0 }, new[] { 0, 0, 6 }, new[] { 0, 0, 0 }, new[] { 0, 1, 1 }, new[] { 0, 4 } };
|
||||
key.Controllers = new SparController[parameters.Length];
|
||||
for (int i = 0; i < parameters.Length; i++)
|
||||
{
|
||||
Require(r, 4);
|
||||
int kind = r.ReadInt32();
|
||||
if ((uint)kind >= (uint)parameters[i].Length)
|
||||
throw new InvalidDataException($"Unknown SPar controller {i}:{kind}");
|
||||
key.Controllers[i] = new SparController { Kind = kind, Parameters = Floats(r, parameters[i][kind]) };
|
||||
}
|
||||
key.Reserved = Floats(r, 4);
|
||||
return key;
|
||||
}
|
||||
|
||||
private static int Count(IBinaryReader r, int maximum)
|
||||
{
|
||||
Require(r, 4);
|
||||
int count = r.ReadInt32();
|
||||
if (count < 0 || count > maximum)
|
||||
throw new InvalidDataException($"Invalid SPar count {count}");
|
||||
return count;
|
||||
}
|
||||
|
||||
private static float[] Floats(IBinaryReader r, int count)
|
||||
{
|
||||
Require(r, checked(count * 4));
|
||||
return r.ReadSingles(count);
|
||||
}
|
||||
|
||||
private static void Require(IBinaryReader r, int count)
|
||||
{
|
||||
if (count > r.Length - r.Position)
|
||||
throw new EndOfStreamException("Truncated SPar file");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 20cca91ba7574724bd67d2fc91b52af8
|
||||
@@ -38,7 +38,7 @@ namespace Pal3.Core.DataReader.Tga
|
||||
*dst = *(src + 2);
|
||||
*(dst + 1) = *(src + 1);
|
||||
*(dst + 2) = *src;
|
||||
*(dst + 3) = 0; // 24-bit don't have alpha
|
||||
*(dst + 3) = 255; // RGB textures sample with opaque alpha, as in GameBox.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -78,9 +78,10 @@ namespace Pal3.Core.DataReader.Tga
|
||||
byte alpha = *(src + 3);
|
||||
*(dst + 3) = alpha;
|
||||
|
||||
if (alpha != firstAlpha) hasAlphaChannel = true;
|
||||
if (alpha != firstAlpha)
|
||||
hasAlphaChannel = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -60,14 +60,17 @@ namespace Pal3.Game.Data
|
||||
|
||||
private ITextureCache _textureCache;
|
||||
|
||||
private readonly Dictionary<string, ISprite> _spriteCache = new ();
|
||||
private readonly Dictionary<string, AudioClip> _audioClipCache = new ();
|
||||
private readonly Dictionary<string, ISprite> _spriteCache = new();
|
||||
private readonly Dictionary<string, AudioClip> _audioClipCache = new();
|
||||
|
||||
private readonly Dictionary<Type, Dictionary<string, object>> _gameResourceFileCache = new ();
|
||||
private readonly Dictionary<Type, Dictionary<string, object>> _gameResourceFileCache = new();
|
||||
|
||||
private readonly int _codepage;
|
||||
|
||||
internal OptionalVfxPlayer OptionalVfx { get; }
|
||||
internal EffectRuntime Effects
|
||||
{
|
||||
get;
|
||||
}
|
||||
|
||||
public GameResourceProvider(ICpkFileSystem fileSystem,
|
||||
ITextureLoaderFactory textureLoaderFactory,
|
||||
@@ -83,7 +86,7 @@ namespace Pal3.Game.Data
|
||||
|
||||
_codepage = _gameSettings.Language == Language.SimplifiedChinese ? 936 : 950;
|
||||
_gameDatabase = GetGameDatabaseFile(); // Initialize game database file
|
||||
OptionalVfx = new OptionalVfxPlayer(_gameSettings);
|
||||
Effects = new EffectRuntime(_fileSystem, _codepage);
|
||||
|
||||
CommandExecutorRegistry<ICommand>.Instance.Register(this);
|
||||
}
|
||||
@@ -112,7 +115,7 @@ namespace Pal3.Game.Data
|
||||
}
|
||||
_audioClipCache.Clear();
|
||||
|
||||
OptionalVfx.Dispose();
|
||||
Effects.Dispose();
|
||||
|
||||
_materialManager.Dispose();
|
||||
|
||||
@@ -131,9 +134,11 @@ namespace Pal3.Game.Data
|
||||
|
||||
// No need to deallocate the shadow texture/sprite since it is been used almost every where.
|
||||
private static ISprite _shadowSprite;
|
||||
|
||||
public ISprite GetShadowSprite()
|
||||
{
|
||||
if (_shadowSprite != null) return _shadowSprite;
|
||||
if (_shadowSprite != null)
|
||||
return _shadowSprite;
|
||||
|
||||
ITexture2D shadowTexture = new UnityTexture2D(Resources.Load<Texture2D>("Textures/shadow"));
|
||||
_shadowSprite = shadowTexture.CreateSprite(0, 0,
|
||||
@@ -143,6 +148,8 @@ namespace Pal3.Game.Data
|
||||
return _shadowSprite;
|
||||
}
|
||||
|
||||
public Effect.Original.OriginalEffectResources OriginalEffects => Effects.Original;
|
||||
|
||||
public IMaterialManager GetMaterialManager() => _materialManager;
|
||||
|
||||
public ITextureResourceProvider CreateTextureResourceProvider(string relativeDirectoryPath, bool useCache = true, TextureUsage usage = TextureUsage.World)
|
||||
@@ -224,7 +231,8 @@ namespace Pal3.Game.Data
|
||||
/// <param name="musicFileCachePath">music file path in cache folder</param>
|
||||
public IEnumerator ExtractAndMoveMp3FileToCacheFolderAsync(string musicFileVirtualPath, string musicFileCachePath)
|
||||
{
|
||||
if (File.Exists(musicFileCachePath)) yield break;
|
||||
if (File.Exists(musicFileCachePath))
|
||||
yield break;
|
||||
|
||||
EngineLogger.Log($"Writing MP3 file to App's persistent folder: {musicFileVirtualPath}");
|
||||
Thread dataMovementThread = new(() =>
|
||||
@@ -253,11 +261,11 @@ namespace Pal3.Game.Data
|
||||
|
||||
public string GetSfxFilePath(string sfxName)
|
||||
{
|
||||
#if PAL3
|
||||
#if PAL3
|
||||
string sfxFileName = (sfxName + ".wav").ToLower();
|
||||
#elif PAL3A
|
||||
#elif PAL3A
|
||||
string sfxFileName = (sfxName + ".wav").ToUpper();
|
||||
#endif
|
||||
#endif
|
||||
|
||||
string sfxFileRelativePath = $"{FileConstants.SfxFolderName}{Path.DirectorySeparatorChar}" + sfxFileName;
|
||||
|
||||
@@ -293,13 +301,13 @@ namespace Pal3.Game.Data
|
||||
|
||||
public ISprite GetLogoSprite()
|
||||
{
|
||||
#if PAL3
|
||||
#if PAL3
|
||||
const string mainLogoTextureFileName = "11.tga";
|
||||
Rect mainLogoSpriteRect = new Rect(0, 600, 375, 145);
|
||||
#elif PAL3A
|
||||
#elif PAL3A
|
||||
const string mainLogoTextureFileName = "12.tga";
|
||||
Rect mainLogoSpriteRect = new Rect(0, 770, 500, 253);
|
||||
#endif
|
||||
#endif
|
||||
|
||||
ITextureResourceProvider uiLibTextureProvider = CreateTextureResourceProvider(FileConstants.UILibFolderVirtualPath, usage: TextureUsage.Sprite);
|
||||
ITexture2D logoTexture = uiLibTextureProvider.GetTexture(mainLogoTextureFileName);
|
||||
@@ -321,13 +329,15 @@ namespace Pal3.Game.Data
|
||||
|
||||
if (_spriteCache.TryGetValue(cacheKey, out ISprite sprite))
|
||||
{
|
||||
if (sprite is { Texture: { IsNativeObjectDisposed: false } }) return sprite;
|
||||
if (sprite is { Texture: { IsNativeObjectDisposed: false } })
|
||||
return sprite;
|
||||
}
|
||||
|
||||
ITexture2D texture = GetActorAvatarTexture(
|
||||
actorName, avatarName);
|
||||
|
||||
if (texture == null) return null;
|
||||
if (texture == null)
|
||||
return null;
|
||||
|
||||
ISprite avatarSprite = texture.CreateSprite(
|
||||
// Cut 2f to hide artifacts near edges for some of the avatar textures
|
||||
@@ -527,6 +537,7 @@ namespace Pal3.Game.Data
|
||||
}
|
||||
|
||||
private string _currentCityName;
|
||||
|
||||
public void Execute(ScenePreLoadingNotification notification)
|
||||
{
|
||||
string newCityName = notification.NewSceneInfo.CityName.ToLower();
|
||||
@@ -590,8 +601,8 @@ namespace Pal3.Game.Data
|
||||
}
|
||||
}
|
||||
|
||||
OptionalVfx.ClearPrefabCache();
|
||||
Effects.InvalidatePreloads();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -513,8 +513,6 @@ namespace Pal3.Game.Dev
|
||||
value => _gameSettings.ToonFireShadows = value);
|
||||
AddOption("泛光", () => _gameSettings.BloomEnabled,
|
||||
value => _gameSettings.BloomEnabled = value);
|
||||
AddOption("可选剧情特效", () => _gameSettings.OptionalVfxEnabled,
|
||||
value => _gameSettings.OptionalVfxEnabled = value);
|
||||
|
||||
CreateMenuButton("返回", _ => delegate
|
||||
{
|
||||
|
||||
@@ -8,30 +8,9 @@ namespace Pal3.Game.Effect
|
||||
using System;
|
||||
using Data;
|
||||
using Engine.Core.Implementation;
|
||||
using Engine.Extensions;
|
||||
|
||||
using Vector3 = UnityEngine.Vector3;
|
||||
|
||||
public sealed class CombatEffect : GameEntityScript, IEffect
|
||||
{
|
||||
#if PAL3
|
||||
private const string SHUSHAN_BRIDGE_TEXTURE_NAME = "q08qiao.dds";
|
||||
#elif PAL3A
|
||||
private const string SHUSHAN_BRIDGE_TEXTURE_NAME = "q08qiao.tga";
|
||||
#endif
|
||||
private const float SHUSHAN_BRIDGE_DEFAULT_SIZE = 3.5f;
|
||||
private const float SHUSHAN_BRIDGE_ANIMATION_ROTATION_SPEED = 15f;
|
||||
|
||||
#if PAL3
|
||||
private const string SHUSHAN_BRIDGE_EFFECT_TEXTURE_NAME = "q08qiao2.dds";
|
||||
#elif PAL3A
|
||||
private const string SHUSHAN_BRIDGE_EFFECT_TEXTURE_NAME = "q08qiao2.tga";
|
||||
#endif
|
||||
private const float SHUSHAN_BRIDGE_EFFECT_DEFAULT_SIZE = 3.5f;
|
||||
private const float SHUSHAN_BRIDGE_EFFECT_ANIMATION_ROTATION_SPEED = 40f;
|
||||
|
||||
private RotatingSpriteEffect _bridgeBaseEffect;
|
||||
private RotatingSpriteEffect _bridgeEffect;
|
||||
private IDisposable _effect;
|
||||
|
||||
protected override void OnDisableGameEntity()
|
||||
@@ -41,59 +20,16 @@ namespace Pal3.Game.Effect
|
||||
|
||||
public void Init(GameResourceProvider resourceProvider, uint effectParameter)
|
||||
{
|
||||
#if PAL3
|
||||
if (effectParameter == 465) // 蜀山太极桥特效
|
||||
#elif PAL3A
|
||||
if (effectParameter == 160) // 蜀山太极桥特效
|
||||
#endif
|
||||
{
|
||||
_bridgeBaseEffect = GameEntity.AddComponent<RotatingSpriteEffect>();
|
||||
_bridgeBaseEffect.Init(resourceProvider,
|
||||
SHUSHAN_BRIDGE_TEXTURE_NAME,
|
||||
new Vector3(SHUSHAN_BRIDGE_DEFAULT_SIZE,
|
||||
SHUSHAN_BRIDGE_DEFAULT_SIZE,
|
||||
SHUSHAN_BRIDGE_DEFAULT_SIZE),
|
||||
SHUSHAN_BRIDGE_ANIMATION_ROTATION_SPEED);
|
||||
|
||||
_bridgeEffect = GameEntity.AddComponent<RotatingSpriteEffect>();
|
||||
_bridgeEffect.Init(resourceProvider,
|
||||
SHUSHAN_BRIDGE_EFFECT_TEXTURE_NAME,
|
||||
new Vector3(SHUSHAN_BRIDGE_EFFECT_DEFAULT_SIZE,
|
||||
SHUSHAN_BRIDGE_EFFECT_DEFAULT_SIZE,
|
||||
SHUSHAN_BRIDGE_EFFECT_DEFAULT_SIZE),
|
||||
SHUSHAN_BRIDGE_EFFECT_ANIMATION_ROTATION_SPEED);
|
||||
}
|
||||
|
||||
#if PAL3
|
||||
if (effectParameter == 275) // 重楼创建的用来禁锢雪见/龙葵的法阵特效
|
||||
#elif PAL3A
|
||||
if (effectParameter == 344) // 重盘古元灵特效
|
||||
#endif
|
||||
{
|
||||
_effect = resourceProvider.OptionalVfx.Attach((int)effectParameter, GameEntity);
|
||||
}
|
||||
// Scene effects use the same native group scheduler as script effects.
|
||||
_effect = resourceProvider.Effects.Attach((int)effectParameter, GameEntity);
|
||||
}
|
||||
|
||||
private void OnDestroy() => Dispose();
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_bridgeBaseEffect != null)
|
||||
{
|
||||
_bridgeBaseEffect.Dispose();
|
||||
_bridgeBaseEffect.Destroy();
|
||||
_bridgeBaseEffect = null;
|
||||
}
|
||||
|
||||
if (_bridgeEffect != null)
|
||||
{
|
||||
_bridgeEffect.Dispose();
|
||||
_bridgeEffect.Destroy();
|
||||
_bridgeEffect = null;
|
||||
}
|
||||
|
||||
_effect?.Dispose();
|
||||
_effect = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,9 +30,12 @@ namespace Pal3.Game.Effect
|
||||
ICommandExecutor<SceneLeavingCurrentSceneNotification>,
|
||||
ICommandExecutor<ResetGameStateCommand>
|
||||
{
|
||||
private readonly OptionalVfxPlayer _optionalVfx;
|
||||
private readonly EffectRuntime _effects;
|
||||
private readonly SceneManager _sceneManager;
|
||||
private ICommand _effectPositionCommand;
|
||||
#if PAL3A
|
||||
private EffectAttachToActorCommand _attachedActor;
|
||||
#endif
|
||||
private Vector3 _originalPosition;
|
||||
|
||||
private const string EFFECT_LINKER_FILE_NAME = "efflinker.dat";
|
||||
private EffectLinkerFile _effectLinkerFile;
|
||||
@@ -40,7 +43,7 @@ namespace Pal3.Game.Effect
|
||||
public EffectManager(GameResourceProvider resourceProvider,
|
||||
SceneManager sceneManager)
|
||||
{
|
||||
_optionalVfx = Requires.IsNotNull(resourceProvider, nameof(resourceProvider)).OptionalVfx;
|
||||
_effects = Requires.IsNotNull(resourceProvider, nameof(resourceProvider)).Effects;
|
||||
_sceneManager = Requires.IsNotNull(sceneManager, nameof(sceneManager));
|
||||
|
||||
_effectLinkerFile = resourceProvider.GetGameResourceFile<EffectLinkerFile>(
|
||||
@@ -61,48 +64,27 @@ namespace Pal3.Game.Effect
|
||||
// So it is pointless to pre-load the effect here for PAL3A.
|
||||
// Even with a waiter, we need to make sure waiter's current execution mode is set
|
||||
// to synchronous otherwise the effect will be played before the pre-load is finished.
|
||||
#if PAL3
|
||||
Pal3.Instance.StartCoroutine(_optionalVfx.PreloadAsync(command.EffectGroupId));
|
||||
#endif
|
||||
#if PAL3
|
||||
Pal3.Instance.StartCoroutine(_effects.PreloadAsync(command.EffectGroupId));
|
||||
#endif
|
||||
}
|
||||
|
||||
public void Execute(EffectPlayCommand command)
|
||||
{
|
||||
if (_effectPositionCommand == null ||
|
||||
_sceneManager.GetCurrentScene() is not {} currentScene) return;
|
||||
|
||||
#if PAL3A
|
||||
if (_effectPositionCommand is EffectAttachToActorCommand effectAttachToActorCommand)
|
||||
{
|
||||
HandleNanGongHuangTransformEffect(effectAttachToActorCommand, command, currentScene);
|
||||
}
|
||||
#endif
|
||||
|
||||
if (_effectPositionCommand is EffectSetPositionCommand positionCommand)
|
||||
{
|
||||
Vector3 localPosition = new GameBoxVector3(
|
||||
positionCommand.GameBoxXPosition,
|
||||
positionCommand.GameBoxYPosition,
|
||||
positionCommand.GameBoxZPosition).ToUnityPosition();
|
||||
|
||||
_optionalVfx.Play(command.EffectGroupId,
|
||||
_sceneManager.GetSceneRootGameEntity(), localPosition);
|
||||
}
|
||||
else if (_effectPositionCommand is EffectAttachToActorCommand actorCommand)
|
||||
{
|
||||
_optionalVfx.Play(command.EffectGroupId,
|
||||
currentScene.GetActorGameEntity(actorCommand.ActorId), Vector3.zero);
|
||||
}
|
||||
|
||||
// Play SFX if any
|
||||
if (EffectConstants.EffectSfxInfo.TryGetValue(command.EffectGroupId, out var sfxName))
|
||||
{
|
||||
Pal3.Instance.Execute(
|
||||
new PlaySfxCommand(sfxName, 1));
|
||||
}
|
||||
if (_sceneManager.GetCurrentScene() is not { } currentScene)
|
||||
return;
|
||||
#if PAL3A
|
||||
if (_attachedActor is { } attach &&
|
||||
!currentScene.GetActorGameEntity(attach.ActorId).IsNullOrDisposed())
|
||||
HandleNanGongHuangTransformEffect(attach, command, currentScene);
|
||||
#endif
|
||||
// Both games retain the last position when cmd_CEft_Role cannot find
|
||||
// its actor. Playback uses that snapshot even if the actor is gone.
|
||||
_effects.Play(command.EffectGroupId,
|
||||
_sceneManager.GetSceneRootGameEntity(), _originalPosition);
|
||||
}
|
||||
|
||||
#if PAL3A
|
||||
#if PAL3A
|
||||
private void HandleNanGongHuangTransformEffect(EffectAttachToActorCommand effectAttachToActorCommand,
|
||||
EffectPlayCommand effectPlayCommand,
|
||||
GameScene currentScene)
|
||||
@@ -138,11 +120,32 @@ namespace Pal3.Game.Effect
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
public void Execute(EffectSetPositionCommand command) => _effectPositionCommand = command;
|
||||
public void Execute(EffectSetPositionCommand command)
|
||||
{
|
||||
#if PAL3A
|
||||
_attachedActor = null;
|
||||
#endif
|
||||
_originalPosition = new GameBoxVector3(command.GameBoxXPosition, command.GameBoxYPosition, command.GameBoxZPosition).ToUnityPosition();
|
||||
}
|
||||
|
||||
public void Execute(EffectAttachToActorCommand command) => _effectPositionCommand = command;
|
||||
public void Execute(EffectAttachToActorCommand command)
|
||||
{
|
||||
#if PAL3A
|
||||
_attachedActor = command;
|
||||
#endif
|
||||
var scene = _sceneManager.GetCurrentScene();
|
||||
var actor = scene?.GetActorGameEntity(command.ActorId);
|
||||
if (!actor.IsNullOrDisposed())
|
||||
{
|
||||
var root = (UnityEngine.Transform)_sceneManager.GetSceneRootGameEntity().Transform.NativeObject;
|
||||
var transform = (UnityEngine.Transform)actor.Transform.NativeObject;
|
||||
// cmd_CEft_Role captures the position immediately and adds two
|
||||
// GameBox units. It does not attach the effect to a moving actor.
|
||||
_originalPosition = root.InverseTransformPoint(transform.position) + Vector3.up * 0.1f;
|
||||
}
|
||||
}
|
||||
|
||||
public void Execute(SceneLeavingCurrentSceneNotification command) => ClearSceneEffects();
|
||||
|
||||
@@ -150,8 +153,11 @@ namespace Pal3.Game.Effect
|
||||
|
||||
private void ClearSceneEffects()
|
||||
{
|
||||
_effectPositionCommand = null;
|
||||
_optionalVfx.ClearPlayedEffects();
|
||||
#if PAL3A
|
||||
_attachedActor = null;
|
||||
#endif
|
||||
_originalPosition = Vector3.zero;
|
||||
_effects.ClearPlayedEffects();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
// ------------------------------------------------------------------------
|
||||
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
|
||||
// See LICENSE file in the project root for license information.
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
namespace Pal3.Game.Effect
|
||||
{
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using Original;
|
||||
using Core.FileSystem;
|
||||
using Core.Command.SceCommands;
|
||||
using Engine.Core.Abstraction;
|
||||
using Engine.Core.Implementation;
|
||||
using Engine.Extensions;
|
||||
using Engine.Logging;
|
||||
using UnityEngine;
|
||||
|
||||
internal sealed class EffectRuntime : IDisposable
|
||||
{
|
||||
private readonly OriginalEffectResources _original;
|
||||
private readonly HashSet<int> _failures = new();
|
||||
private readonly List<IGameEntity> _playedEffects = new();
|
||||
private readonly List<PersistentEffect> _persistentEffects = new();
|
||||
private int _preloadGeneration;
|
||||
private bool _disposed;
|
||||
|
||||
internal OriginalEffectResources Original => _original;
|
||||
|
||||
internal EffectRuntime(ICpkFileSystem fileSystem, int codepage)
|
||||
{
|
||||
_original = new OriginalEffectResources(fileSystem, codepage);
|
||||
}
|
||||
|
||||
internal IEnumerator PreloadAsync(int groupId)
|
||||
{
|
||||
if (_disposed)
|
||||
yield break;
|
||||
int generation = _preloadGeneration;
|
||||
OriginalEffectOverrides edits;
|
||||
try
|
||||
{
|
||||
edits = Resources.Load<OriginalEffectOverrides>(_original.OverridesPath);
|
||||
string[] issues = _original.Diagnose(groupId, edits);
|
||||
if (issues.Length != 0)
|
||||
{
|
||||
Report(groupId, string.Join("\n", issues));
|
||||
yield break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Report(groupId, ex.Message);
|
||||
yield break;
|
||||
}
|
||||
using var preload = _original.Preload(groupId, edits).GetEnumerator();
|
||||
while (!_disposed && generation == _preloadGeneration)
|
||||
{
|
||||
bool next;
|
||||
try
|
||||
{
|
||||
next = preload.MoveNext();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Report(groupId, ex.Message);
|
||||
break;
|
||||
}
|
||||
if (!next)
|
||||
break;
|
||||
yield return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void Report(int groupId, string message)
|
||||
{
|
||||
if (_failures.Add(groupId))
|
||||
EngineLogger.LogWarning($"Effect {groupId}: {message}");
|
||||
}
|
||||
|
||||
private IGameEntity Create(int groupId, IGameEntity parent, uint portalType = 0)
|
||||
{
|
||||
if (_disposed || parent.IsNullOrDisposed())
|
||||
return null;
|
||||
GameObject root = null;
|
||||
try
|
||||
{
|
||||
var edits = Resources.Load<OriginalEffectOverrides>(_original.OverridesPath);
|
||||
string[] issues = groupId == -1 ? Array.Empty<string>() : _original.Diagnose(groupId, edits);
|
||||
if (issues.Length != 0)
|
||||
{
|
||||
Report(groupId, string.Join("\n", issues));
|
||||
return null;
|
||||
}
|
||||
root = new GameObject(groupId == -1 ? "Original transport" : $"Original effect {groupId}");
|
||||
root.transform.SetParent((Transform)parent.Transform.NativeObject, false);
|
||||
if (groupId == -1)
|
||||
root.AddComponent<OriginalPortalEffect>().Initialize(_original, portalType);
|
||||
else
|
||||
{
|
||||
var player = root.AddComponent<OriginalEffectPlayer>();
|
||||
player.Initialize(_original, groupId, (uint)UnityEngine.Random.Range(1, int.MaxValue), overrides: edits,
|
||||
sound: name => Pal3.Instance.Execute(new PlaySfxCommand(name, 1)));
|
||||
player.DestroyOnComplete = true;
|
||||
if (player.Error != null)
|
||||
throw new InvalidOperationException(player.Error);
|
||||
}
|
||||
return new GameEntity(root);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (root != null)
|
||||
{
|
||||
root.SetActive(false);
|
||||
OriginalEffectResources.Destroy(root);
|
||||
}
|
||||
Report(groupId, ex.Message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
internal bool Play(int groupId, IGameEntity parent, Vector3 localPosition)
|
||||
{
|
||||
if (Create(groupId, parent) is not { } instance)
|
||||
return false;
|
||||
instance.Transform.LocalPosition += localPosition;
|
||||
_playedEffects.RemoveAll(effect => effect.IsNativeObjectDisposed);
|
||||
_playedEffects.Add(instance);
|
||||
return true;
|
||||
}
|
||||
|
||||
internal IDisposable AttachPortal(IGameEntity parent, uint type = 0) => Attach(-1, parent, type);
|
||||
|
||||
internal IDisposable Attach(int groupId, IGameEntity parent, uint portalType = 0)
|
||||
{
|
||||
if (_disposed || parent.IsNullOrDisposed())
|
||||
return null;
|
||||
PruneDeadAttachments();
|
||||
var effect = new PersistentEffect(this, groupId, parent, portalType);
|
||||
_persistentEffects.Add(effect);
|
||||
return effect;
|
||||
}
|
||||
|
||||
internal void ClearPlayedEffects()
|
||||
{
|
||||
foreach (IGameEntity effect in _playedEffects)
|
||||
Stop(effect);
|
||||
_playedEffects.Clear();
|
||||
InvalidatePreloads();
|
||||
_failures.Clear();
|
||||
if (_disposed)
|
||||
return;
|
||||
if (Application.isPlaying && Pal3.Instance != null)
|
||||
Pal3.Instance.StartCoroutine(TrimSceneRenderAssetsAfterFrame());
|
||||
else
|
||||
_original.TrimUnusedRenderAssets(LiveRoots());
|
||||
}
|
||||
|
||||
private IEnumerator TrimSceneRenderAssetsAfterFrame()
|
||||
{
|
||||
// Scene objects are destroyed at the end of the leaving frame.
|
||||
yield return null;
|
||||
if (_disposed)
|
||||
yield break;
|
||||
PruneDeadAttachments();
|
||||
_original.TrimUnusedRenderAssets(LiveRoots());
|
||||
}
|
||||
|
||||
private IEnumerable<GameObject> LiveRoots()
|
||||
{
|
||||
foreach (IGameEntity effect in _playedEffects)
|
||||
if (!effect.IsNullOrDisposed())
|
||||
yield return (GameObject)effect.NativeObject;
|
||||
foreach (PersistentEffect effect in _persistentEffects)
|
||||
if (effect.Root != null)
|
||||
yield return effect.Root;
|
||||
}
|
||||
|
||||
private static void Stop(IGameEntity effect)
|
||||
{
|
||||
if (effect.IsNullOrDisposed())
|
||||
return;
|
||||
((GameObject)effect.NativeObject).SetActive(false);
|
||||
effect.Destroy();
|
||||
}
|
||||
|
||||
private void PruneDeadAttachments()
|
||||
{
|
||||
for (int i = _persistentEffects.Count - 1; i >= 0; i--)
|
||||
if (_persistentEffects[i].ParentIsDisposed)
|
||||
_persistentEffects[i].Dispose();
|
||||
}
|
||||
|
||||
internal void InvalidatePreloads()
|
||||
{
|
||||
PruneDeadAttachments();
|
||||
_preloadGeneration++;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
return;
|
||||
_disposed = true;
|
||||
ClearPlayedEffects();
|
||||
foreach (PersistentEffect effect in _persistentEffects.ToArray())
|
||||
effect.Dispose();
|
||||
_original.Dispose();
|
||||
}
|
||||
|
||||
private sealed class PersistentEffect : IDisposable
|
||||
{
|
||||
private readonly EffectRuntime _owner;
|
||||
private readonly IGameEntity _parent;
|
||||
private IGameEntity _instance;
|
||||
|
||||
internal bool ParentIsDisposed => _parent.IsNullOrDisposed();
|
||||
|
||||
internal GameObject Root => _instance.IsNullOrDisposed() ? null : (GameObject)_instance.NativeObject;
|
||||
|
||||
internal PersistentEffect(EffectRuntime owner, int groupId, IGameEntity parent, uint portalType)
|
||||
{
|
||||
_owner = owner;
|
||||
_parent = parent;
|
||||
_instance = owner.Create(groupId, parent, portalType);
|
||||
if (Root != null && Root.GetComponent<OriginalEffectPlayer>() is { } player)
|
||||
{
|
||||
player.DestroyOnComplete = false;
|
||||
player.Loop = true;
|
||||
player.RepeatInterval = owner._original.GameVariant == "PAL3" && groupId == 275 ? 9.5f : 0;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_owner._persistentEffects.Remove(this);
|
||||
Stop(_instance);
|
||||
_instance = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -1,198 +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
|
||||
{
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using Constants;
|
||||
using Engine.Core.Abstraction;
|
||||
using Engine.Core.Implementation;
|
||||
using Engine.Extensions;
|
||||
using Engine.Logging;
|
||||
using Settings;
|
||||
using UnityEngine;
|
||||
|
||||
internal sealed class OptionalVfxPlayer : IDisposable
|
||||
{
|
||||
private readonly GameSettings _settings;
|
||||
private readonly Dictionary<int, GameObject> _prefabs = new();
|
||||
private readonly List<IGameEntity> _playedEffects = new();
|
||||
private readonly List<PersistentEffect> _persistentEffects = new();
|
||||
|
||||
private int _prefabCacheGeneration;
|
||||
private bool _disposed;
|
||||
private bool IsEnabled => !_disposed && _settings.OptionalVfxEnabled;
|
||||
|
||||
internal OptionalVfxPlayer(GameSettings settings)
|
||||
{
|
||||
_settings = settings;
|
||||
_settings.OnGameSettingsChanged += OnGameSettingsChanged;
|
||||
}
|
||||
|
||||
private static string GetPrefabPath(int effectGroupId) => $"Prefabs/VFX/{GameConstants.AppName}/{effectGroupId}";
|
||||
|
||||
internal IEnumerator PreloadAsync(int effectGroupId)
|
||||
{
|
||||
if (!IsEnabled || _prefabs.ContainsKey(effectGroupId)) yield break;
|
||||
|
||||
int generation = _prefabCacheGeneration;
|
||||
ResourceRequest request = Resources.LoadAsync<GameObject>(GetPrefabPath(effectGroupId));
|
||||
yield return request;
|
||||
|
||||
if (IsEnabled && generation == _prefabCacheGeneration && !_prefabs.ContainsKey(effectGroupId))
|
||||
{
|
||||
CachePrefab(effectGroupId, request.asset as GameObject);
|
||||
}
|
||||
}
|
||||
|
||||
private void CachePrefab(int effectGroupId, GameObject prefab)
|
||||
{
|
||||
_prefabs[effectGroupId] = prefab;
|
||||
if (prefab == null)
|
||||
{
|
||||
EngineLogger.LogWarning($"VFX prefab not found: {effectGroupId}");
|
||||
}
|
||||
}
|
||||
|
||||
private IGameEntity Create(int effectGroupId, IGameEntity parent)
|
||||
{
|
||||
if (!IsEnabled || parent.IsNullOrDisposed()) return null;
|
||||
|
||||
if (!_prefabs.TryGetValue(effectGroupId, out GameObject prefab))
|
||||
{
|
||||
prefab = Resources.Load<GameObject>(GetPrefabPath(effectGroupId));
|
||||
CachePrefab(effectGroupId, prefab);
|
||||
}
|
||||
|
||||
return prefab == null ? null :
|
||||
GameEntityFactory.Create($"VFX_{effectGroupId}", prefab, parent, worldPositionStays: false);
|
||||
}
|
||||
|
||||
internal void Play(int effectGroupId, IGameEntity parent, Vector3 localPosition)
|
||||
{
|
||||
if (Create(effectGroupId, parent) is not {} instance) return;
|
||||
|
||||
instance.Transform.LocalPosition += localPosition;
|
||||
_playedEffects.RemoveAll(effect => effect.IsNativeObjectDisposed);
|
||||
_playedEffects.Add(instance);
|
||||
}
|
||||
|
||||
internal IDisposable Attach(int effectGroupId, IGameEntity parent)
|
||||
{
|
||||
if (_disposed || parent.IsNullOrDisposed()) return null;
|
||||
PruneDeadAttachments();
|
||||
var effect = new PersistentEffect(this, effectGroupId, parent);
|
||||
_persistentEffects.Add(effect);
|
||||
effect.Refresh();
|
||||
return effect;
|
||||
}
|
||||
|
||||
private void OnGameSettingsChanged(string propertyName)
|
||||
{
|
||||
if (propertyName != nameof(GameSettings.OptionalVfxEnabled)) return;
|
||||
|
||||
if (!IsEnabled) ClearPlayedEffects();
|
||||
|
||||
foreach (PersistentEffect effect in _persistentEffects.ToArray())
|
||||
{
|
||||
effect.Refresh();
|
||||
}
|
||||
}
|
||||
|
||||
internal void ClearPlayedEffects()
|
||||
{
|
||||
foreach (IGameEntity effect in _playedEffects)
|
||||
{
|
||||
Stop(effect);
|
||||
}
|
||||
_playedEffects.Clear();
|
||||
}
|
||||
|
||||
private static void Stop(IGameEntity effect)
|
||||
{
|
||||
if (effect.IsNullOrDisposed()) return;
|
||||
|
||||
// Destroy is deferred to the end of the frame.
|
||||
((GameObject)effect.NativeObject).SetActive(false);
|
||||
effect.Destroy();
|
||||
}
|
||||
|
||||
private void PruneDeadAttachments()
|
||||
{
|
||||
for (int i = _persistentEffects.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (_persistentEffects[i].ParentIsDisposed) _persistentEffects[i].Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
internal void ClearPrefabCache()
|
||||
{
|
||||
PruneDeadAttachments();
|
||||
_prefabCacheGeneration++;
|
||||
_prefabs.Clear();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_disposed = true;
|
||||
_settings.OnGameSettingsChanged -= OnGameSettingsChanged;
|
||||
ClearPlayedEffects();
|
||||
|
||||
foreach (PersistentEffect effect in _persistentEffects.ToArray())
|
||||
{
|
||||
effect.Dispose();
|
||||
}
|
||||
ClearPrefabCache();
|
||||
}
|
||||
|
||||
private sealed class PersistentEffect : IDisposable
|
||||
{
|
||||
private readonly OptionalVfxPlayer _player;
|
||||
private readonly int _effectGroupId;
|
||||
private readonly IGameEntity _parent;
|
||||
private IGameEntity _instance;
|
||||
private bool _disposed;
|
||||
|
||||
internal PersistentEffect(OptionalVfxPlayer player, int effectGroupId, IGameEntity parent)
|
||||
{
|
||||
_player = player;
|
||||
_effectGroupId = effectGroupId;
|
||||
_parent = parent;
|
||||
}
|
||||
|
||||
internal bool ParentIsDisposed => _parent.IsNullOrDisposed();
|
||||
|
||||
internal void Refresh()
|
||||
{
|
||||
if (_disposed) return;
|
||||
if (ParentIsDisposed)
|
||||
{
|
||||
Dispose();
|
||||
return;
|
||||
}
|
||||
|
||||
if (_player.IsEnabled)
|
||||
{
|
||||
if (_instance.IsNullOrDisposed()) _instance = _player.Create(_effectGroupId, _parent);
|
||||
}
|
||||
else
|
||||
{
|
||||
Stop(_instance);
|
||||
_instance = null;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_disposed = true;
|
||||
_player._persistentEffects.Remove(this);
|
||||
Stop(_instance);
|
||||
_instance = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ce61acd16e807473ea038ae337099077
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,86 @@
|
||||
// ------------------------------------------------------------------------
|
||||
// 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 System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
|
||||
internal sealed class EffectMeshBuffer : IDisposable
|
||||
{
|
||||
private readonly Mesh _mesh;
|
||||
private readonly bool _reverseWinding;
|
||||
private readonly MeshRenderer _renderer;
|
||||
private readonly List<Vector3> _vertices = new();
|
||||
private readonly List<Vector2> _uv = new();
|
||||
private readonly List<Color32> _colors = new();
|
||||
private readonly List<int> _indices = new();
|
||||
|
||||
public int QuadCount => _vertices.Count / 4;
|
||||
|
||||
public EffectMeshBuffer(GameObject root, Material material, bool reverseWinding = false)
|
||||
{
|
||||
_reverseWinding = reverseWinding;
|
||||
_mesh = new Mesh { name = "Original effect mesh", indexFormat = IndexFormat.UInt32, hideFlags = HideFlags.DontSave };
|
||||
_mesh.MarkDynamic();
|
||||
root.AddComponent<MeshFilter>().sharedMesh = _mesh;
|
||||
_renderer = root.AddComponent<MeshRenderer>();
|
||||
_renderer.sharedMaterial = material;
|
||||
_renderer.shadowCastingMode = ShadowCastingMode.Off;
|
||||
_renderer.receiveShadows = false;
|
||||
_renderer.lightProbeUsage = LightProbeUsage.Off;
|
||||
_renderer.reflectionProbeUsage = ReflectionProbeUsage.Off;
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_vertices.Clear();
|
||||
_uv.Clear();
|
||||
_colors.Clear();
|
||||
_indices.Clear();
|
||||
}
|
||||
|
||||
public void Quad(Vector3 a, Vector3 b, Vector3 c, Vector3 d, Vector2 uv0, Vector2 uv1, Color32 color)
|
||||
=> Quad(a, b, c, d, uv0, uv1, color, color, color, color);
|
||||
|
||||
public void Quad(Vector3 a, Vector3 b, Vector3 c, Vector3 d, Vector2 uv0, Vector2 uv1,
|
||||
Color32 colorA, Color32 colorB, Color32 colorC, Color32 colorD)
|
||||
{
|
||||
int n = _vertices.Count;
|
||||
_vertices.Add(a);
|
||||
_vertices.Add(b);
|
||||
_vertices.Add(c);
|
||||
_vertices.Add(d);
|
||||
_uv.Add(uv0);
|
||||
_uv.Add(new Vector2(uv1.x, uv0.y));
|
||||
_uv.Add(uv1);
|
||||
_uv.Add(new Vector2(uv0.x, uv1.y));
|
||||
_colors.Add(colorA);
|
||||
_colors.Add(colorB);
|
||||
_colors.Add(colorC);
|
||||
_colors.Add(colorD);
|
||||
_indices.Add(n);
|
||||
_indices.Add(n + (_reverseWinding ? 2 : 1));
|
||||
_indices.Add(n + (_reverseWinding ? 1 : 2));
|
||||
_indices.Add(n);
|
||||
_indices.Add(n + (_reverseWinding ? 3 : 2));
|
||||
_indices.Add(n + (_reverseWinding ? 2 : 3));
|
||||
}
|
||||
|
||||
public void Upload()
|
||||
{
|
||||
_renderer.enabled = _vertices.Count > 0;
|
||||
_mesh.Clear(false);
|
||||
_mesh.SetVertices(_vertices);
|
||||
_mesh.SetUVs(0, _uv);
|
||||
_mesh.SetColors(_colors);
|
||||
_mesh.SetTriangles(_indices, 0, true);
|
||||
}
|
||||
|
||||
public void Dispose() => OriginalEffectResources.Destroy(_mesh);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4daa7814a3fa8493293fc2ad9eb6fecc
|
||||
@@ -0,0 +1,193 @@
|
||||
// ------------------------------------------------------------------------
|
||||
// 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 Core.DataReader.Data;
|
||||
using UnityEngine;
|
||||
using Color = UnityEngine.Color;
|
||||
|
||||
internal sealed class OriginalTaskClock
|
||||
{
|
||||
private bool _initialized, _finished;
|
||||
private float _initAt;
|
||||
|
||||
public float StartedAt { get; private set; } = -1;
|
||||
|
||||
public bool StartedNow
|
||||
{
|
||||
get; private set;
|
||||
}
|
||||
|
||||
public bool Finished => _finished;
|
||||
|
||||
public bool Tick(float time, float dt, EffectTask task, out float elapsed)
|
||||
{
|
||||
StartedNow = false;
|
||||
elapsed = 0;
|
||||
if (_finished)
|
||||
return false;
|
||||
if (!_initialized)
|
||||
{
|
||||
_initialized = true;
|
||||
_initAt = time;
|
||||
// A negative wait means "after the previous init subtask",
|
||||
// which has already finished in this update in CTaskTpl.
|
||||
if (task.StartTime >= 0)
|
||||
return false;
|
||||
StartedAt = time;
|
||||
StartedNow = true;
|
||||
}
|
||||
if (StartedAt < 0)
|
||||
{
|
||||
if (time - _initAt <= Mathf.Max(0, task.StartTime))
|
||||
return false;
|
||||
StartedAt = time;
|
||||
StartedNow = true;
|
||||
}
|
||||
elapsed = dt - Mathf.Max(0, time - StartedAt - task.Duration);
|
||||
_finished = time - StartedAt + 0.000001f >= task.Duration;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
internal abstract class OriginalEffectNode : IDisposable
|
||||
{
|
||||
protected readonly GameObject Root;
|
||||
protected readonly EffectDefinition Definition;
|
||||
protected readonly EffectTask[] Tasks;
|
||||
protected readonly OriginalTaskClock[] Clocks;
|
||||
protected readonly float Birth;
|
||||
protected Vector3 Position, Rotation, Orbit, Scale;
|
||||
protected Color Tint;
|
||||
protected float TextureOffset, LocalTime;
|
||||
protected bool Visible;
|
||||
|
||||
public virtual bool Alive { get; protected set; } = true;
|
||||
public virtual int QuadCount => 0;
|
||||
|
||||
protected OriginalEffectNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth)
|
||||
{
|
||||
Root = root;
|
||||
Definition = d;
|
||||
Tasks = tasks ?? Array.Empty<EffectTask>();
|
||||
Birth = birth;
|
||||
Position = origin + new Vector3(d.InitXPosition, d.InitYPosition, d.InitZPosition);
|
||||
Rotation = new Vector3(d.InitXRotation, d.InitYRotation, d.InitZRotation);
|
||||
Scale = Vector3.one * d.InitSize;
|
||||
Tint = PackedColor(d.InitColor);
|
||||
Clocks = new OriginalTaskClock[Tasks.Length];
|
||||
for (int i = 0; i < Clocks.Length; i++)
|
||||
Clocks[i] = new OriginalTaskClock();
|
||||
}
|
||||
|
||||
public virtual void Step(float time, float dt)
|
||||
{
|
||||
LocalTime = time - Birth;
|
||||
bool alive = false;
|
||||
for (int i = 0; i < Tasks.Length; i++)
|
||||
{
|
||||
if (Clocks[i].Tick(LocalTime, dt, Tasks[i], out float activeDt))
|
||||
{
|
||||
Visible = true;
|
||||
Apply(Tasks[i], Clocks[i], Mathf.Max(0, activeDt));
|
||||
}
|
||||
alive |= !Clocks[i].Finished;
|
||||
}
|
||||
Alive = alive;
|
||||
}
|
||||
|
||||
protected virtual void Apply(EffectTask t, OriginalTaskClock clock, float dt)
|
||||
{
|
||||
Position += new Vector3(t.SpeedX, t.SpeedY, t.SpeedZ) * dt;
|
||||
ApplyRotationAndStretch(t, dt);
|
||||
Tint = ChangedColor(Tint, t, dt);
|
||||
Vector3 axis = new(t.CircleAxisX, t.CircleAxisY, t.CircleAxisZ);
|
||||
Orbit = OrbitPosition(axis, (LocalTime - clock.StartedAt) * t.CircleSpeed, t.CircleRadius);
|
||||
TextureOffset += t.CreateTimeSlot * dt;
|
||||
}
|
||||
|
||||
protected virtual void ApplyRotationAndStretch(EffectTask t, float dt)
|
||||
{
|
||||
Rotation += new Vector3(t.RotAxisX, t.RotAxisY, t.RotAxisZ) * dt;
|
||||
Scale += new Vector3(t.XStretchSpeed, t.YStretchSpeed, t.CreateTimeSlot) * dt;
|
||||
}
|
||||
|
||||
public abstract void Render(Camera camera);
|
||||
|
||||
public virtual void Dispose()
|
||||
{
|
||||
if (Root != null)
|
||||
Root.SetActive(false);
|
||||
OriginalEffectResources.Destroy(Root);
|
||||
}
|
||||
|
||||
internal static Vector3 UnityPosition(Vector3 v) => new(-v.x / 20, v.y / 20, v.z / 20);
|
||||
|
||||
// A zero axis produces an identity matrix in GameBox, preserving the
|
||||
// input radius vector rather than discarding the offset.
|
||||
internal static Vector3 OrbitPosition(Vector3 axis, float angle, float radius) =>
|
||||
(axis.sqrMagnitude > 0 ? Quaternion.AngleAxis(angle, axis.normalized) : Quaternion.identity) * new Vector3(0, 0, radius);
|
||||
|
||||
internal static Quaternion UnityRotation(Vector3 r) => Quaternion.AngleAxis(r.x, Vector3.right) * Quaternion.AngleAxis(-r.y, Vector3.up) * Quaternion.AngleAxis(-r.z, Vector3.forward);
|
||||
|
||||
internal static Quaternion RawRotation(Vector3 r) => Quaternion.AngleAxis(r.x, Vector3.right) * Quaternion.AngleAxis(r.y, Vector3.up) * Quaternion.AngleAxis(r.z, Vector3.forward);
|
||||
|
||||
internal static Color PackedColor(uint c) => new((c >> 16 & 255) / 255f, (c >> 8 & 255) / 255f, (c & 255) / 255f, (c >> 24) / 255f);
|
||||
|
||||
internal static Color ChangedColor(Color c, EffectTask t, float dt) => new(Mathf.Clamp01(c.r + t.SpeedRed * dt / 255),
|
||||
Mathf.Clamp01(c.g + t.SpeedGreen * dt / 255), Mathf.Clamp01(c.b + t.SpeedBlue * dt / 255), Mathf.Clamp01(c.a + t.SpeedAlpha * dt / 255));
|
||||
|
||||
protected (Vector2 min, Vector2 max) Atlas(float age)
|
||||
{
|
||||
int columns = Mathf.Max(1, Definition.FramesPerRow), rows = Mathf.Max(1, Definition.FramesPerColumn);
|
||||
int frame = Mathf.Abs(Mathf.RoundToInt(age * Definition.FramePerSecond)) % Mathf.Max(1, Definition.FrameCount);
|
||||
var uv = new Vector2((float)(frame % columns) / columns, 1f - (float)(frame / columns + 1) / rows);
|
||||
return (uv, uv + new Vector2(1f / columns, 1f / rows));
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class OriginalControlNode : OriginalEffectNode
|
||||
{
|
||||
private readonly OriginalEffectPlayer _player;
|
||||
private readonly string _kind;
|
||||
private readonly byte[] _played;
|
||||
|
||||
public OriginalControlNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, OriginalEffectPlayer player, string kind)
|
||||
: base(root, d, tasks, origin, birth)
|
||||
{
|
||||
_player = player;
|
||||
_kind = kind;
|
||||
_played = new byte[Tasks.Length];
|
||||
}
|
||||
|
||||
protected override void Apply(EffectTask t, OriginalTaskClock clock, float dt)
|
||||
{
|
||||
if (_kind == "callback")
|
||||
{
|
||||
if (clock.StartedNow)
|
||||
foreach (var child in t.Callbacks())
|
||||
_player.AddGroup(child.groupId, Position + new Vector3(child.position.X, child.position.Y, child.position.Z));
|
||||
}
|
||||
else
|
||||
{
|
||||
int index = Array.IndexOf(Tasks, t), bit = 0;
|
||||
foreach (var sound in t.Sounds())
|
||||
{
|
||||
int mask = 1 << bit++;
|
||||
if ((_played[index] & mask) != 0 || LocalTime - clock.StartedAt < sound.delay)
|
||||
continue;
|
||||
_player.Sound($"{Definition.SfxFileNamePrefix}{sound.index:000}");
|
||||
_played[index] |= (byte)mask;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void Render(Camera camera)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 03437bbaa78854faca572e1b314a630a
|
||||
@@ -0,0 +1,133 @@
|
||||
// ------------------------------------------------------------------------
|
||||
// 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 System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Core.DataReader.Data;
|
||||
using Core.DataReader.Par;
|
||||
using UnityEngine;
|
||||
|
||||
[Serializable]
|
||||
public sealed class OriginalEffectObjectOverride
|
||||
{
|
||||
public int GroupId, ObjectIndex;
|
||||
public EffectDefinition Definition;
|
||||
public EffectTask[] Tasks;
|
||||
public bool Hidden;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class OriginalParticleCurveOverride
|
||||
{
|
||||
public string File, Parameter;
|
||||
public bool Emitter;
|
||||
public int Index;
|
||||
public AnimationCurve[] Channels;
|
||||
}
|
||||
|
||||
[CreateAssetMenu(menuName = "PAL3/Original effect overrides")]
|
||||
public sealed class OriginalEffectOverrides : ScriptableObject
|
||||
{
|
||||
public int Version = 1;
|
||||
public List<OriginalEffectObjectOverride> Objects = new();
|
||||
public List<OriginalParticleCurveOverride> ParticleCurves = new();
|
||||
|
||||
public OriginalEffectObjectOverride Find(int group, int index) =>
|
||||
Objects.Find(o => o.GroupId == group && o.ObjectIndex == index);
|
||||
|
||||
internal static bool Resolve(OriginalEffectOverrides edits, int group, int index,
|
||||
ref EffectDefinition definition, ref EffectTask[] tasks)
|
||||
{
|
||||
if (edits != null && edits.Version != 1)
|
||||
throw new NotSupportedException($"Unknown original effect override version {edits.Version}");
|
||||
OriginalEffectObjectOverride edit = edits?.Find(group, index);
|
||||
if (edit?.Hidden == true)
|
||||
return false;
|
||||
if (edit != null)
|
||||
{
|
||||
definition = edit.Definition;
|
||||
tasks = edit.Tasks ?? throw new InvalidOperationException("Missing effect override tasks");
|
||||
ValidateNumbers(new[] { definition.InitXPosition, definition.InitYPosition, definition.InitZPosition,
|
||||
definition.InitXRotation, definition.InitYRotation, definition.InitZRotation, definition.InitSize,
|
||||
definition.FramePerSecond, definition.RotationAngle, definition.Width, definition.DivisionCount,
|
||||
definition.TopShrink, definition.BottomShrink, definition.TopRadius, definition.BottomRadius,
|
||||
definition.TopRadiusIncreaseSpeed, definition.BottomRadiusIncreaseSpeed, definition.TopRiseSpeed,
|
||||
definition.BottomRiseSpeed, definition.TextureRepeat });
|
||||
if (tasks.Length > 8)
|
||||
throw new InvalidOperationException("An original effect object supports at most eight tasks");
|
||||
foreach (EffectTask t in tasks.Where(t => t != null && t.IsValid))
|
||||
{
|
||||
ValidateNumbers(new[] { t.XStretchSpeed, t.SpeedX, t.SpeedY, t.SpeedZ, t.SpeedRot,
|
||||
t.CircleAxisX, t.CircleAxisY, t.CircleAxisZ, t.CircleRadius, t.CircleSpeed,
|
||||
t.RotAxisX, t.RotAxisY, t.RotAxisZ, t.RotSpeed, t.SpeedAlpha, t.SpeedRed,
|
||||
t.SpeedGreen, t.SpeedBlue, t.StartTime, t.Duration, t.CreateTimeSlot, t.YStretchSpeed });
|
||||
if (t.Duration < 0)
|
||||
throw new InvalidOperationException("An effect task duration cannot be negative");
|
||||
}
|
||||
}
|
||||
tasks = tasks.Where(t => t != null && t.IsValid).ToArray();
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void ValidateNumbers(IEnumerable<float> values)
|
||||
{
|
||||
if (values.Any(v => !float.IsFinite(v)))
|
||||
throw new InvalidOperationException("Effect overrides require finite numeric parameters");
|
||||
}
|
||||
|
||||
public bool HasParticleEdits(string file) => ParticleCurves.Exists(c =>
|
||||
string.Equals(OriginalEffectResources.Normalize(c.File), OriginalEffectResources.Normalize(file), StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
public void ApplyParticle(string path, ParticleFile file)
|
||||
{
|
||||
foreach (OriginalParticleCurveOverride edit in ParticleCurves)
|
||||
{
|
||||
if (!string.Equals(OriginalEffectResources.Normalize(edit.File), OriginalEffectResources.Normalize(path), StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
ParticleCurve curve = FindCurve(file, edit.Emitter, edit.Index, edit.Parameter);
|
||||
if (edit.Channels == null || edit.Channels.Length != curve.Channels || edit.Channels.Any(c => c == null))
|
||||
throw new InvalidOperationException("Particle curve channel count does not match original data");
|
||||
foreach (AnimationCurve channel in edit.Channels)
|
||||
{
|
||||
ValidateNumbers(channel.keys.SelectMany(k => new[] { k.time, k.value }));
|
||||
// Infinite tangents are valid stepped keys. Evaluate the
|
||||
// normalized interval to reject curves that produce NaN/Inf.
|
||||
ValidateNumbers(Enumerable.Range(0, 101).Select(i => channel.Evaluate(i / 100f)));
|
||||
}
|
||||
curve.OverrideEvaluation = (time, channel) => channel >= 0 && channel < edit.Channels.Length ? edit.Channels[channel].Evaluate(time) : 0;
|
||||
}
|
||||
}
|
||||
|
||||
public static ParticleCurve FindCurve(ParticleFile file, bool emitter, int index, string name)
|
||||
{
|
||||
if (emitter)
|
||||
{
|
||||
ParticleEmitter e = file.Emitters[index];
|
||||
return name switch
|
||||
{
|
||||
"Direction" => e.Direction,
|
||||
"RandomVelocity" => e.RandomVelocity,
|
||||
"Emission" => e.Emission,
|
||||
"Life" => e.Life,
|
||||
"Size" => e.Size,
|
||||
"Rotation" => e.Rotation,
|
||||
_ => throw new ArgumentException(name)
|
||||
};
|
||||
}
|
||||
ParticleDescription p = file.Particles[index];
|
||||
return name switch
|
||||
{
|
||||
"Size" => p.Size,
|
||||
"Rotation" => p.Rotation,
|
||||
"Alpha" => p.Alpha,
|
||||
"Color" => p.Color,
|
||||
_ => throw new ArgumentException(name)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3a0f5edeb37f04ad28e5e2ed9000e2c5
|
||||
@@ -0,0 +1,296 @@
|
||||
// ------------------------------------------------------------------------
|
||||
// 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 System.Collections.Generic;
|
||||
using Core.DataReader.Data;
|
||||
using UnityEngine;
|
||||
|
||||
// One simulation serves both clocks: real frame time in game, and fixed
|
||||
// steps for editor playback/seeking. Rendering never advances the clock.
|
||||
public sealed class OriginalEffectPlayer : MonoBehaviour
|
||||
{
|
||||
public const float FixedStep = 0.02f;
|
||||
private readonly List<OriginalEffectNode> _nodes = new();
|
||||
private OriginalEffectResources _resources;
|
||||
private OriginalEffectOverrides _overrides;
|
||||
private int _groupId;
|
||||
private double _time;
|
||||
private uint _seed;
|
||||
private uint _spawnSequence;
|
||||
private float _accumulator;
|
||||
private Action<string> _sound;
|
||||
private bool _disposed, _suppressEvents;
|
||||
private float _lastRepeat;
|
||||
|
||||
public float Time => (float)_time;
|
||||
public bool AutoAdvance { get; set; } = true;
|
||||
|
||||
public bool Paused
|
||||
{
|
||||
get; set;
|
||||
}
|
||||
|
||||
public float Speed { get; set; } = 1;
|
||||
|
||||
public bool Loop
|
||||
{
|
||||
get; set;
|
||||
}
|
||||
|
||||
public bool DestroyOnComplete
|
||||
{
|
||||
get; set;
|
||||
}
|
||||
|
||||
public float RepeatInterval
|
||||
{
|
||||
get; set;
|
||||
}
|
||||
|
||||
public int NodeCount => _nodes.Count;
|
||||
|
||||
public int QuadCount
|
||||
{
|
||||
get; private set;
|
||||
}
|
||||
|
||||
public bool IsAlive
|
||||
{
|
||||
get; private set;
|
||||
}
|
||||
|
||||
public string Error
|
||||
{
|
||||
get; private set;
|
||||
}
|
||||
|
||||
public void Initialize(OriginalEffectResources resources, int groupId, uint seed = 1,
|
||||
OriginalEffectOverrides overrides = null, Action<string> sound = null)
|
||||
{
|
||||
if (overrides != null && overrides.Version != 1)
|
||||
throw new NotSupportedException($"Unknown original effect override version {overrides.Version}");
|
||||
_resources = resources;
|
||||
_groupId = groupId;
|
||||
_seed = seed == 0 ? 1 : seed;
|
||||
_overrides = overrides;
|
||||
_sound = sound;
|
||||
ResetSimulation();
|
||||
}
|
||||
|
||||
private void ResetSimulation(bool resetRandom = true)
|
||||
{
|
||||
ClearNodes();
|
||||
_time = 0;
|
||||
_accumulator = 0;
|
||||
_lastRepeat = 0;
|
||||
Error = null;
|
||||
if (resetRandom)
|
||||
_spawnSequence = 0;
|
||||
try
|
||||
{
|
||||
AddGroup(_groupId, Vector3.zero);
|
||||
IsAlive = _nodes.Count > 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Error = ex.Message;
|
||||
ClearNodes();
|
||||
IsAlive = false;
|
||||
}
|
||||
}
|
||||
|
||||
internal void AddGroup(int groupId, Vector3 position)
|
||||
{
|
||||
if (groupId < 0 || groupId >= _resources.Definitions.Groups.Length)
|
||||
throw new ArgumentOutOfRangeException(nameof(groupId));
|
||||
EffectGroup group = _resources.Definitions.Groups[groupId];
|
||||
for (int i = 0; i < group.Objects.Length; i++)
|
||||
{
|
||||
EffectGroupObject obj = group.Objects[i];
|
||||
_resources.Definitions.TryGetType(obj.TypeCrc, out EffectDefinition d);
|
||||
EffectTask[] tasks = obj.Tasks;
|
||||
if (!OriginalEffectOverrides.Resolve(_overrides, groupId, i, ref d, ref tasks))
|
||||
continue;
|
||||
if (_nodes.Count >= 2048)
|
||||
throw new InvalidOperationException("Original effect object limit (2048) reached");
|
||||
obj = new EffectGroupObject { TypeCrc = obj.TypeCrc, Tasks = tasks };
|
||||
var root = new GameObject($"{groupId}:{i} {d.TypeName}") { hideFlags = HideFlags.DontSave, layer = gameObject.layer };
|
||||
root.transform.SetParent(transform, false);
|
||||
OriginalEffectNode node = null;
|
||||
try
|
||||
{
|
||||
string kind = EffectClass.Name(d.ClassNameCrc);
|
||||
uint seed = _seed + _spawnSequence++ * 7919 + (uint)(groupId * 104729 + i);
|
||||
node = kind switch
|
||||
{
|
||||
"callback" or "audio" => new OriginalControlNode(root, d, obj.Tasks, position, Time, this, kind),
|
||||
"quad" => new OriginalQuadNode(root, d, obj.Tasks, position, Time, _resources),
|
||||
"S-Particle" => new OriginalSparNode(root, d, obj.Tasks, position, Time, _resources, seed),
|
||||
"particle" => new OriginalParticleNode(root, d, obj.Tasks, position, Time, _resources, seed, _overrides),
|
||||
"cylinder" or "grid" => new OriginalGeometryNode(root, d, obj.Tasks, position, Time, _resources, kind),
|
||||
"meteor" or "shock" => new OriginalTrailNode(root, d, obj.Tasks, position, Time, _resources, kind, seed),
|
||||
"model" => new OriginalModelNode(root, d, obj.Tasks, position, Time, _resources),
|
||||
"explosive" => new OriginalExplosiveNode(root, d, obj.Tasks, position, Time, _resources, seed),
|
||||
_ => throw new NotSupportedException($"Original effect class {kind}: {d.TypeName}"),
|
||||
};
|
||||
_nodes.Add(node);
|
||||
}
|
||||
catch
|
||||
{
|
||||
node?.Dispose();
|
||||
OriginalEffectResources.Destroy(root);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal void Sound(string name)
|
||||
{
|
||||
if (!_suppressEvents)
|
||||
_sound?.Invoke(name);
|
||||
}
|
||||
|
||||
public void Advance(float delta)
|
||||
{
|
||||
float elapsed = ScaledDelta(delta);
|
||||
if (elapsed <= 0)
|
||||
return;
|
||||
_accumulator += elapsed;
|
||||
while (_accumulator + 0.000001f >= FixedStep)
|
||||
{
|
||||
_accumulator -= FixedStep;
|
||||
if (!SimulateStep(FixedStep))
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public void AdvanceFrame(float delta)
|
||||
{
|
||||
float elapsed = ScaledDelta(delta);
|
||||
if (elapsed <= 0)
|
||||
return;
|
||||
elapsed += _accumulator;
|
||||
_accumulator = 0;
|
||||
SimulateStep(elapsed);
|
||||
}
|
||||
|
||||
private float ScaledDelta(float delta)
|
||||
{
|
||||
if (_disposed || Paused || Error != null || delta <= 0 || !float.IsFinite(delta))
|
||||
return 0;
|
||||
float elapsed = delta * (float.IsFinite(Speed) ? Mathf.Clamp(Speed, 0, 16) : 1);
|
||||
return float.IsFinite(elapsed) ? elapsed : 0;
|
||||
}
|
||||
|
||||
private bool SimulateStep(float delta)
|
||||
{
|
||||
_time += delta;
|
||||
try
|
||||
{
|
||||
int count = _nodes.Count;
|
||||
bool alive = false;
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
_nodes[i].Step(Time, delta);
|
||||
alive |= _nodes[i].Alive;
|
||||
}
|
||||
IsAlive = alive || _nodes.Count > count;
|
||||
for (int i = _nodes.Count - 1; i >= 0; i--)
|
||||
if (!_nodes[i].Alive)
|
||||
{
|
||||
_nodes[i].Dispose();
|
||||
_nodes.RemoveAt(i);
|
||||
}
|
||||
if (Loop && RepeatInterval > 0 && Time - _lastRepeat >= RepeatInterval)
|
||||
{
|
||||
AddGroup(_groupId, Vector3.zero);
|
||||
_lastRepeat = Time;
|
||||
IsAlive = true;
|
||||
}
|
||||
if (Loop && !IsAlive && RepeatInterval <= 0)
|
||||
{
|
||||
ResetSimulation(false);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Error = ex.ToString();
|
||||
ClearNodes();
|
||||
IsAlive = false;
|
||||
Debug.LogException(ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void Seek(float time)
|
||||
{
|
||||
if (_disposed)
|
||||
return;
|
||||
time = Mathf.Clamp(float.IsFinite(time) ? time : 0, 0, 600);
|
||||
bool paused = Paused, loop = Loop;
|
||||
float speed = Speed;
|
||||
ResetSimulation();
|
||||
Paused = false;
|
||||
Loop = false;
|
||||
Speed = 1;
|
||||
_suppressEvents = true;
|
||||
try
|
||||
{
|
||||
Advance(time);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_suppressEvents = false;
|
||||
Paused = paused;
|
||||
Loop = loop;
|
||||
Speed = speed;
|
||||
}
|
||||
}
|
||||
|
||||
public void Render(Camera camera)
|
||||
{
|
||||
QuadCount = 0;
|
||||
foreach (OriginalEffectNode node in _nodes)
|
||||
{
|
||||
node.Render(camera);
|
||||
QuadCount += node.QuadCount;
|
||||
}
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (!AutoAdvance)
|
||||
return;
|
||||
AdvanceFrame(UnityEngine.Time.deltaTime);
|
||||
if (DestroyOnComplete && !Loop && !IsAlive && Time > 0)
|
||||
OriginalEffectResources.Destroy(gameObject);
|
||||
}
|
||||
|
||||
private void LateUpdate()
|
||||
{
|
||||
if (AutoAdvance)
|
||||
Render(Camera.main);
|
||||
}
|
||||
|
||||
private void ClearNodes()
|
||||
{
|
||||
foreach (OriginalEffectNode node in _nodes)
|
||||
node.Dispose();
|
||||
_nodes.Clear();
|
||||
QuadCount = 0;
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
_disposed = true;
|
||||
ClearNodes();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7b4e14dc881ee4e348d1125f142c9dc4
|
||||
@@ -0,0 +1,463 @@
|
||||
// ------------------------------------------------------------------------
|
||||
// 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 System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Core.DataReader;
|
||||
using Core.DataReader.Data;
|
||||
using Core.DataReader.Cvd;
|
||||
using Core.DataReader.Par;
|
||||
using Core.DataReader.Pol;
|
||||
using Core.FileSystem;
|
||||
using Data;
|
||||
using Engine.Core.Implementation;
|
||||
using Engine.Core.Abstraction;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
|
||||
public sealed class OriginalEffectResources : IDisposable
|
||||
{
|
||||
private readonly ICpkFileSystem _fileSystem;
|
||||
private readonly int _codepage;
|
||||
private readonly Dictionary<string, Texture2D> _textures = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<string, ParticleFile> _particles = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<string, byte[]> _particleBytes = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<string, ParticleFile> _overrideParticles = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<string, ParticleShapeFile> _shapes = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<string, PolFile> _polModels = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<string, SparFile> _sparFiles = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<string, CvdFile> _models = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<(string, int, int, bool, int, int), Material> _materials = new();
|
||||
private readonly Dictionary<int, string[]> _diagnostics = new();
|
||||
private readonly Dictionary<int, string[]> _overrideDiagnostics = new();
|
||||
private OriginalEffectOverrides _cachedOverrides;
|
||||
private string _cachedOverridesJson;
|
||||
private EffectDefinitionFile _definitions;
|
||||
|
||||
public EffectDefinitionFile Definitions => _definitions ??= Read<EffectDefinitionFile>("cbdata\\flexeff.data", new EffectDefinitionFileReader());
|
||||
|
||||
public string GameVariant => Definitions.EffectDefinitions.Length == 2048 ? "PAL3A" : "PAL3";
|
||||
|
||||
public string OverridesPath => $"Effects/{GameVariant}Overrides";
|
||||
|
||||
public OriginalEffectResources(ICpkFileSystem fileSystem, int codepage = 936)
|
||||
{
|
||||
_fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem));
|
||||
_codepage = codepage;
|
||||
}
|
||||
|
||||
public static string Normalize(string path)
|
||||
{
|
||||
path = path.Replace('/', '\\');
|
||||
return path.StartsWith("basedata.cpk\\", StringComparison.OrdinalIgnoreCase) ? path : "basedata.cpk\\" + path;
|
||||
}
|
||||
|
||||
public byte[] Bytes(string path) => _fileSystem.ReadAllBytes(Normalize(path));
|
||||
|
||||
public T Read<T>(string path, IFileReader<T> reader) => reader.Read(Bytes(path), _codepage);
|
||||
|
||||
public ITextureResourceProvider ModelTextureProvider(string file) => new ModelTextures(this, file);
|
||||
|
||||
private sealed class ModelTextures : ITextureResourceProvider
|
||||
{
|
||||
private readonly OriginalEffectResources _owner;
|
||||
private readonly string _file;
|
||||
|
||||
public ModelTextures(OriginalEffectResources owner, string file)
|
||||
{
|
||||
_owner = owner;
|
||||
_file = file;
|
||||
}
|
||||
|
||||
public string GetTexturePath(string name) => RelativeTo(_file, name);
|
||||
|
||||
public ITexture2D GetTexture(string name) => GetTexture(name, out _);
|
||||
|
||||
public ITexture2D GetTexture(string name, out bool hasAlphaChannel)
|
||||
{
|
||||
hasAlphaChannel = true;
|
||||
return new UnityTexture2D(_owner.Texture(GetTexturePath(name)));
|
||||
}
|
||||
}
|
||||
|
||||
public ParticleFile Particle(string path, OriginalEffectOverrides edits = null)
|
||||
{
|
||||
path = Normalize(path);
|
||||
if (!_particles.TryGetValue(path, out ParticleFile file))
|
||||
{
|
||||
if (!_particleBytes.TryGetValue(path, out byte[] bytes))
|
||||
_particleBytes[path] = bytes = Bytes(path);
|
||||
_particles[path] = file = ((IFileReader<ParticleFile>)new ParticleFileReader()).Read(bytes, _codepage);
|
||||
}
|
||||
if (edits != null && edits.HasParticleEdits(path))
|
||||
{
|
||||
RefreshOverrideCache(edits);
|
||||
if (!_overrideParticles.TryGetValue(path, out ParticleFile copy))
|
||||
{
|
||||
copy = ((IFileReader<ParticleFile>)new ParticleFileReader()).Read(_particleBytes[path], _codepage);
|
||||
edits.ApplyParticle(path, copy);
|
||||
_overrideParticles[path] = copy;
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
private void RefreshOverrideCache(OriginalEffectOverrides edits)
|
||||
{
|
||||
// Public override fields also support scripts, Undo and the native
|
||||
// Inspector. A content stamp catches those edits without relying on
|
||||
// every caller to manually invalidate a revision counter.
|
||||
string json = JsonUtility.ToJson(edits);
|
||||
if (ReferenceEquals(edits, _cachedOverrides) && json == _cachedOverridesJson)
|
||||
return;
|
||||
_cachedOverrides = edits;
|
||||
_cachedOverridesJson = json;
|
||||
_overrideDiagnostics.Clear();
|
||||
_overrideParticles.Clear();
|
||||
}
|
||||
|
||||
public ParticleShapeFile Shape(string path)
|
||||
{
|
||||
if (!_shapes.TryGetValue(path, out ParticleShapeFile file))
|
||||
_shapes.Add(path, file = Read(path, new ParticleShapeFileReader()));
|
||||
return file;
|
||||
}
|
||||
|
||||
public SparFile Spar(string path)
|
||||
{
|
||||
if (!_sparFiles.TryGetValue(path, out SparFile file))
|
||||
_sparFiles.Add(path, file = Read(path, new SparFileReader()));
|
||||
return file;
|
||||
}
|
||||
|
||||
public PolFile PolModel(string path)
|
||||
{
|
||||
if (!_polModels.TryGetValue(path, out PolFile file))
|
||||
_polModels.Add(path, file = Read(path, new PolFileReader()));
|
||||
return file;
|
||||
}
|
||||
|
||||
public CvdFile Model(string path)
|
||||
{
|
||||
if (!_models.TryGetValue(path, out CvdFile file))
|
||||
_models.Add(path, file = Read(path, new CvdFileReader()));
|
||||
return file;
|
||||
}
|
||||
|
||||
public static string RelativeTo(string file, string relative)
|
||||
{
|
||||
file = file.Replace('/', '\\');
|
||||
int slash = file.LastIndexOf('\\');
|
||||
return (slash < 0 ? "" : file[..(slash + 1)]) + relative.Replace('/', '\\');
|
||||
}
|
||||
|
||||
public string ResolveTexture(string path)
|
||||
{
|
||||
path = Normalize(path);
|
||||
string dds = Path.ChangeExtension(path, ".dds");
|
||||
if (_fileSystem.FileExists(dds))
|
||||
return dds;
|
||||
if (_fileSystem.FileExists(path))
|
||||
return path;
|
||||
throw new FileNotFoundException($"Original effect texture not found: {path}", path);
|
||||
}
|
||||
|
||||
public Texture2D Texture(string path)
|
||||
{
|
||||
path = ResolveTexture(path);
|
||||
if (_textures.TryGetValue(path, out Texture2D cached))
|
||||
return cached;
|
||||
Texture2D texture;
|
||||
if (path.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".png", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
texture = new Texture2D(2, 2, TextureFormat.RGBA32, false);
|
||||
if (!texture.LoadImage(Bytes(path), true))
|
||||
{
|
||||
Destroy(texture);
|
||||
throw new InvalidDataException($"Invalid image {path}");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var provider = new TextureProvider(_fileSystem, new TextureLoaderFactory(), new UnityTextureFactory(),
|
||||
"basedata.cpk", usage: TextureUsage.Sprite);
|
||||
texture = provider.GetTexture(path["basedata.cpk\\".Length..])?.NativeObject as Texture2D;
|
||||
if (texture == null)
|
||||
throw new InvalidDataException($"Could not load original effect texture {path}");
|
||||
}
|
||||
texture.name = path;
|
||||
texture.wrapMode = TextureWrapMode.Repeat;
|
||||
texture.hideFlags = HideFlags.DontSave;
|
||||
_textures.Add(path, texture);
|
||||
return texture;
|
||||
}
|
||||
|
||||
public Material Material(string texture, bool additive, bool noZ, int alphaMode = 0) =>
|
||||
RenderMaterial(texture, alphaMode == 1 ? BlendMode.One : BlendMode.SrcAlpha,
|
||||
additive ? BlendMode.One : BlendMode.OneMinusSrcAlpha, noZ, alphaMode, CullMode.Off);
|
||||
|
||||
// gfxscript/Particle{1,2,3,NotBlend}.gbf: both color and alpha modulate.
|
||||
public Material SparMaterial(string texture, int shader) => shader switch
|
||||
{
|
||||
1 => RenderMaterial(texture, BlendMode.SrcAlpha, BlendMode.DstAlpha, false, 0, CullMode.Back),
|
||||
2 => RenderMaterial(texture, BlendMode.SrcAlpha, BlendMode.OneMinusSrcColor, false, 0, CullMode.Back),
|
||||
3 => RenderMaterial(texture, BlendMode.SrcColor, BlendMode.OneMinusSrcColor, false, 0, CullMode.Back),
|
||||
_ => RenderMaterial(texture, BlendMode.One, BlendMode.Zero, false, 0, CullMode.Back)
|
||||
};
|
||||
|
||||
private Material RenderMaterial(string texture, BlendMode source, BlendMode destination, bool noZ, int alphaMode, CullMode cull)
|
||||
{
|
||||
var key = (texture, (int)source, (int)destination, noZ, alphaMode, (int)cull);
|
||||
if (_materials.TryGetValue(key, out Material cached))
|
||||
return cached;
|
||||
Shader shader = Shader.Find("Pal3/OriginalEffect");
|
||||
if (shader == null || !shader.isSupported)
|
||||
throw new InvalidOperationException("OriginalEffect URP shader is unavailable");
|
||||
var material = new Material(shader) { name = $"Original {texture}", hideFlags = HideFlags.DontSave };
|
||||
try
|
||||
{
|
||||
material.mainTexture = string.IsNullOrEmpty(texture) ? Texture2D.whiteTexture : Texture(texture);
|
||||
}
|
||||
catch
|
||||
{
|
||||
Destroy(material);
|
||||
throw;
|
||||
}
|
||||
material.SetInt("_SrcBlend", (int)source);
|
||||
material.SetInt("_DstBlend", (int)destination);
|
||||
material.SetInt("_Cull", (int)cull);
|
||||
material.SetInt("_ZTest", (int)(noZ ? CompareFunction.Always : CompareFunction.LessEqual));
|
||||
material.SetFloat("_AlphaMode", alphaMode);
|
||||
_materials.Add(key, material);
|
||||
return material;
|
||||
}
|
||||
|
||||
// Validate the complete callback closure before choosing this backend.
|
||||
public string[] Diagnose(int groupId, OriginalEffectOverrides edits = null)
|
||||
{
|
||||
if (edits != null)
|
||||
RefreshOverrideCache(edits);
|
||||
Dictionary<int, string[]> cache = edits == null ? _diagnostics : _overrideDiagnostics;
|
||||
if (cache.TryGetValue(groupId, out string[] cached))
|
||||
return cached;
|
||||
var errors = new List<string>();
|
||||
var visiting = new HashSet<int>();
|
||||
var done = new HashSet<int>();
|
||||
void ModelTextures(string path, CvdGeometryNode node)
|
||||
{
|
||||
if (node.IsGeometryNode)
|
||||
foreach (CvdMeshSection section in node.Mesh.MeshSections)
|
||||
{
|
||||
string name = section.Material.TextureFileNames[0];
|
||||
if (!string.IsNullOrEmpty(name))
|
||||
ResolveTexture(RelativeTo(path, name));
|
||||
}
|
||||
foreach (CvdGeometryNode child in node.Children)
|
||||
ModelTextures(path, child);
|
||||
}
|
||||
void Visit(int id)
|
||||
{
|
||||
if (done.Contains(id))
|
||||
return;
|
||||
if (!visiting.Add(id))
|
||||
{
|
||||
errors.Add($"Recursive callback cycle at group {id}");
|
||||
return;
|
||||
}
|
||||
if (id < 0 || id >= Definitions.Groups.Length)
|
||||
{
|
||||
errors.Add($"Group {id} is outside flexeff");
|
||||
visiting.Remove(id);
|
||||
return;
|
||||
}
|
||||
EffectGroupObject[] objects = Definitions.Groups[id].Objects;
|
||||
for (int index = 0; index < objects.Length; index++)
|
||||
{
|
||||
EffectGroupObject obj = objects[index];
|
||||
Definitions.TryGetType(obj.TypeCrc, out EffectDefinition d);
|
||||
try
|
||||
{
|
||||
EffectTask[] tasks = obj.Tasks;
|
||||
if (!OriginalEffectOverrides.Resolve(edits, id, index, ref d, ref tasks))
|
||||
continue;
|
||||
string kind = EffectClass.Name(d.ClassNameCrc);
|
||||
switch (kind)
|
||||
{
|
||||
case "callback":
|
||||
foreach (EffectTask t in tasks)
|
||||
foreach (var child in t.Callbacks())
|
||||
Visit(child.groupId);
|
||||
break;
|
||||
case "audio":
|
||||
break;
|
||||
case "S-Particle":
|
||||
SparFile spar = Spar(d.ParticleFileName);
|
||||
foreach (SparGroup sg in spar.Groups)
|
||||
{
|
||||
OriginalSparEmitter.Validate(sg);
|
||||
ResolveTexture(RelativeTo(d.ParticleFileName, sg.Texture));
|
||||
}
|
||||
break;
|
||||
case "particle":
|
||||
ParticleFile p = Particle(d.ParticleFileName, edits);
|
||||
foreach (ParticleDescription pd in p.Particles)
|
||||
ResolveTexture(RelativeTo(d.ParticleFileName, pd.Texture));
|
||||
foreach (ParticleEmitter e in p.Emitters)
|
||||
if (e.Shape == 2)
|
||||
Shape(RelativeTo(d.ParticleFileName, e.ShapePath));
|
||||
break;
|
||||
case "quad":
|
||||
case "cylinder":
|
||||
case "meteor":
|
||||
case "shock":
|
||||
case "grid":
|
||||
case "explosive":
|
||||
ResolveTexture(d.TextureName);
|
||||
break;
|
||||
case "model":
|
||||
if (d.TextureName.EndsWith(".pol", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
foreach (PolMesh mesh in PolModel(d.TextureName).Meshes)
|
||||
foreach (PolTexture texture in mesh.Textures)
|
||||
foreach (string name in texture.Material.TextureFileNames)
|
||||
if (!string.IsNullOrEmpty(name))
|
||||
ResolveTexture(RelativeTo(d.TextureName, name));
|
||||
}
|
||||
else if (d.TextureName.EndsWith(".cvd", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
foreach (CvdGeometryNode node in Model(d.TextureName).RootNodes)
|
||||
ModelTextures(d.TextureName, node);
|
||||
}
|
||||
else
|
||||
throw new NotSupportedException($"Unknown original model format: {d.TextureName}");
|
||||
break;
|
||||
default:
|
||||
errors.Add($"Group {id}, {d.TypeName}: unsupported original class {kind}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
errors.Add($"Group {id}, {d.TypeName}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
visiting.Remove(id);
|
||||
done.Add(id);
|
||||
}
|
||||
Visit(groupId);
|
||||
string[] result = errors.ToArray();
|
||||
cache[groupId] = result;
|
||||
return result;
|
||||
}
|
||||
|
||||
public IEnumerable<int> Preload(int groupId, OriginalEffectOverrides edits = null)
|
||||
{
|
||||
var seen = new HashSet<int>();
|
||||
var pending = new Stack<int>();
|
||||
pending.Push(groupId);
|
||||
while (pending.Count > 0)
|
||||
{
|
||||
int id = pending.Pop();
|
||||
if (!seen.Add(id))
|
||||
continue;
|
||||
EffectGroupObject[] objects = Definitions.Groups[id].Objects;
|
||||
for (int index = 0; index < objects.Length; index++)
|
||||
{
|
||||
EffectGroupObject obj = objects[index];
|
||||
Definitions.TryGetType(obj.TypeCrc, out EffectDefinition d);
|
||||
EffectTask[] tasks = obj.Tasks;
|
||||
if (!OriginalEffectOverrides.Resolve(edits, id, index, ref d, ref tasks))
|
||||
continue;
|
||||
string kind = EffectClass.Name(d.ClassNameCrc);
|
||||
if (kind == "callback")
|
||||
foreach (EffectTask t in tasks)
|
||||
foreach (var child in t.Callbacks())
|
||||
pending.Push(child.groupId);
|
||||
else if (kind == "particle")
|
||||
foreach (ParticleDescription p in Particle(d.ParticleFileName, edits).Particles)
|
||||
Texture(RelativeTo(d.ParticleFileName, p.Texture));
|
||||
else if (kind == "S-Particle")
|
||||
foreach (SparGroup group in Spar(d.ParticleFileName).Groups)
|
||||
Texture(RelativeTo(d.ParticleFileName, group.Texture));
|
||||
else if (kind != "audio" && kind != "model")
|
||||
Texture(d.TextureName);
|
||||
yield return id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void TrimUnusedRenderAssets(IEnumerable<GameObject> liveRoots)
|
||||
{
|
||||
var materials = new HashSet<Material>();
|
||||
var textures = new HashSet<Texture>();
|
||||
foreach (GameObject root in liveRoots)
|
||||
{
|
||||
if (root == null)
|
||||
continue;
|
||||
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
|
||||
foreach (Material material in renderer.sharedMaterials)
|
||||
{
|
||||
if (material == null)
|
||||
continue;
|
||||
materials.Add(material);
|
||||
// POL materials can also hold a baked lightmap. Every
|
||||
// referenced texture must survive a scene-cache trim.
|
||||
foreach (int property in material.GetTexturePropertyNameIDs())
|
||||
{
|
||||
Texture texture = material.GetTexture(property);
|
||||
if (texture != null)
|
||||
textures.Add(texture);
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (var key in _materials.Where(p => !materials.Contains(p.Value)).Select(p => p.Key).ToArray())
|
||||
{
|
||||
Destroy(_materials[key]);
|
||||
_materials.Remove(key);
|
||||
}
|
||||
foreach (string key in _textures.Where(p => !textures.Contains(p.Value)).Select(p => p.Key).ToArray())
|
||||
{
|
||||
Destroy(_textures[key]);
|
||||
_textures.Remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (Material m in _materials.Values)
|
||||
Destroy(m);
|
||||
foreach (Texture2D t in _textures.Values)
|
||||
Destroy(t);
|
||||
_materials.Clear();
|
||||
_textures.Clear();
|
||||
_particles.Clear();
|
||||
_particleBytes.Clear();
|
||||
_overrideParticles.Clear();
|
||||
_shapes.Clear();
|
||||
_models.Clear();
|
||||
_polModels.Clear();
|
||||
_sparFiles.Clear();
|
||||
_diagnostics.Clear();
|
||||
_overrideDiagnostics.Clear();
|
||||
_cachedOverrides = null;
|
||||
_cachedOverridesJson = null;
|
||||
}
|
||||
|
||||
public static void Destroy(UnityEngine.Object value)
|
||||
{
|
||||
if (value == null)
|
||||
return;
|
||||
if (Application.isPlaying)
|
||||
UnityEngine.Object.Destroy(value);
|
||||
else
|
||||
UnityEngine.Object.DestroyImmediate(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6df74732b3a2d44b69e9ed674b10f621
|
||||
@@ -0,0 +1,129 @@
|
||||
// ------------------------------------------------------------------------
|
||||
// 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 Core.DataReader.Data;
|
||||
using UnityEngine;
|
||||
|
||||
// CEffExplosive: subdivided plane, per-fragment velocity and spin.
|
||||
internal sealed class OriginalExplosiveNode : OriginalEffectNode
|
||||
{
|
||||
private readonly EffectMeshBuffer _mesh;
|
||||
private readonly Vector3[][] _corners;
|
||||
private readonly Vector3[] _velocity, _spin;
|
||||
private readonly bool[] _exploded;
|
||||
private readonly System.Random _random;
|
||||
private readonly int _columns, _rows;
|
||||
|
||||
public override int QuadCount => _mesh.QuadCount;
|
||||
|
||||
public OriginalExplosiveNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, OriginalEffectResources resources, uint seed)
|
||||
: base(root, d, tasks, origin, birth)
|
||||
{
|
||||
_columns = (int)d.RotationAngle;
|
||||
_rows = (int)d.DivisionCount;
|
||||
if (_columns < 1 || _rows < 1 || (long)_columns * _rows >= 2501)
|
||||
throw new InvalidOperationException("Invalid original explosive subdivisions");
|
||||
_mesh = new EffectMeshBuffer(root, resources.Material(d.TextureName, d.IsAdditiveBlend, d.IsZTestIgnored));
|
||||
_random = new System.Random(unchecked((int)seed));
|
||||
_corners = new Vector3[_columns * _rows][];
|
||||
_velocity = new Vector3[_corners.Length];
|
||||
_spin = new Vector3[_corners.Length];
|
||||
_exploded = new bool[Tasks.Length];
|
||||
for (int row = 0; row < _rows; row++)
|
||||
for (int column = 0; column < _columns; column++)
|
||||
{
|
||||
float x = (column - _columns / 2f) * d.Width;
|
||||
float z = (_rows / 2f - row) * d.Width;
|
||||
_corners[row * _columns + column] = new[]
|
||||
{
|
||||
new Vector3(x, 0, z), new Vector3(x + d.Width, 0, z),
|
||||
new Vector3(x + d.Width, 0, z - d.Width), new Vector3(x, 0, z - d.Width)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private void Explode()
|
||||
{
|
||||
int maximum = Mathf.RoundToInt(Definition.TopRadius);
|
||||
if (maximum <= 0)
|
||||
maximum = 2;
|
||||
float minimum = Mathf.Max(0, Definition.BottomRadius);
|
||||
int count = 0;
|
||||
// Preserve the original column/row traversal, including its center indices.
|
||||
for (int column = 0; column < _columns; column++)
|
||||
for (int row = 0; row < _rows; row++, count++)
|
||||
{
|
||||
int power = Mathf.Max(1, Mathf.RoundToInt(Mathf.Max(minimum, maximum -
|
||||
Mathf.Abs(row - _columns / 2) * Mathf.Abs(column - _rows / 2) * Mathf.Max(0, Definition.TopRiseSpeed))));
|
||||
float Component() => _random.Next(power) - power / 2;
|
||||
Vector3 velocity = new(Component(), Component(), Component());
|
||||
if (velocity.magnitude < minimum)
|
||||
velocity = velocity.normalized * minimum;
|
||||
_velocity[count] = velocity + new Vector3(Definition.TopRadiusIncreaseSpeed, Definition.BottomRadiusIncreaseSpeed, Definition.TextureRepeat);
|
||||
float Spin() => (_random.Next(160) - 80) * 16f;
|
||||
_spin[count] = new Vector3(Spin(), Spin(), Spin());
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Apply(EffectTask t, OriginalTaskClock clock, float dt)
|
||||
{
|
||||
Position += new Vector3(t.SpeedX, t.SpeedY, t.SpeedZ) * dt;
|
||||
Rotation += new Vector3(t.RotAxisX, t.RotAxisY, t.RotAxisZ) * dt;
|
||||
Scale += new Vector3(t.XStretchSpeed, 0, t.CreateTimeSlot) * dt;
|
||||
Tint.a = Mathf.Clamp01(Tint.a + t.SpeedAlpha * dt / 255);
|
||||
Orbit = OrbitPosition(new Vector3(t.CircleAxisX, t.CircleAxisY, t.CircleAxisZ), (LocalTime - clock.StartedAt) * t.CircleSpeed, t.CircleRadius);
|
||||
int index = Array.IndexOf(Clocks, clock);
|
||||
if (LocalTime - clock.StartedAt <= t.SpeedRed)
|
||||
return;
|
||||
if (!_exploded[index])
|
||||
{
|
||||
Explode();
|
||||
_exploded[index] = true;
|
||||
}
|
||||
for (int i = 0; i < _corners.Length; i++)
|
||||
{
|
||||
Vector3[] corners = _corners[i];
|
||||
Vector3 center = (corners[0] + corners[1] + corners[2] + corners[3]) / 4;
|
||||
Vector3 moved = center + _velocity[i] * dt;
|
||||
Quaternion rotation = Quaternion.AngleAxis(_spin[i].y * dt, Vector3.right) *
|
||||
Quaternion.AngleAxis(_spin[i].x * dt, Vector3.up) * Quaternion.AngleAxis(_spin[i].z * dt, Vector3.forward);
|
||||
for (int corner = 0; corner < 4; corner++)
|
||||
corners[corner] = moved + rotation * (corners[corner] - center);
|
||||
}
|
||||
}
|
||||
|
||||
public override void Render(Camera camera)
|
||||
{
|
||||
_mesh.Clear();
|
||||
if (Alive && Visible)
|
||||
{
|
||||
var atlas = Atlas(LocalTime);
|
||||
Vector2 step = (atlas.max - atlas.min) / new Vector2(_columns, _rows);
|
||||
Quaternion rotation = RawRotation(Rotation);
|
||||
for (int i = 0; i < _corners.Length; i++)
|
||||
{
|
||||
Vector3 P(int corner)
|
||||
{
|
||||
Vector3 v = rotation * _corners[i][corner];
|
||||
v = Vector3.Scale(v, new Vector3(Scale.x, 1, Scale.z));
|
||||
return UnityPosition(Position + Orbit + v);
|
||||
}
|
||||
Vector2 uv = atlas.min + Vector2.Scale(new Vector2(i % _columns, i / _columns), step);
|
||||
_mesh.Quad(P(0), P(1), P(2), P(3), uv, uv + step, Tint);
|
||||
}
|
||||
}
|
||||
_mesh.Upload();
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
_mesh.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 99a3ca8ca9c646d4b5357809a1f6749d
|
||||
@@ -0,0 +1,128 @@
|
||||
// ------------------------------------------------------------------------
|
||||
// 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 Core.DataReader.Data;
|
||||
using UnityEngine;
|
||||
|
||||
internal sealed class OriginalGeometryNode : OriginalEffectNode
|
||||
{
|
||||
private readonly EffectMeshBuffer _mesh;
|
||||
private readonly string _kind;
|
||||
private readonly Vector3[] _points;
|
||||
private readonly int _columns, _rows;
|
||||
|
||||
public override int QuadCount => _mesh.QuadCount;
|
||||
|
||||
public OriginalGeometryNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, OriginalEffectResources resources, string kind)
|
||||
: base(root, d, tasks, origin, birth)
|
||||
{
|
||||
_kind = kind;
|
||||
Scale = new Vector3(d.InitSize, 1, d.InitSize);
|
||||
_mesh = new EffectMeshBuffer(root, resources.Material(d.TextureName, d.IsAdditiveBlend, d.IsZTestIgnored));
|
||||
if (kind == "cylinder")
|
||||
{
|
||||
_columns = Mathf.Clamp(Mathf.RoundToInt(d.DivisionCount), 1, 4096);
|
||||
_rows = 1;
|
||||
_points = new Vector3[(_columns + 1) * 2];
|
||||
for (int i = 0; i <= _columns; i++)
|
||||
{
|
||||
float a = i * d.RotationAngle / _columns;
|
||||
float top = d.TopRadius + d.TopRadiusIncreaseSpeed * a - (i % 2 == 1 ? d.TopShrink : 0);
|
||||
float bottom = d.BottomRadius + d.BottomRadiusIncreaseSpeed * a - (i % 2 == 1 ? d.BottomShrink : 0);
|
||||
float rad = a * Mathf.Deg2Rad;
|
||||
_points[i * 2] = new Vector3(Mathf.Sin(rad) * bottom, d.BottomRiseSpeed * a, Mathf.Cos(rad) * bottom);
|
||||
_points[i * 2 + 1] = new Vector3(Mathf.Sin(rad) * top, d.Width + d.TopRiseSpeed * a, Mathf.Cos(rad) * top);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_columns = Mathf.Clamp(Mathf.RoundToInt(d.RotationAngle), 1, 128);
|
||||
_rows = Mathf.Clamp(Mathf.RoundToInt(d.DivisionCount), 1, 128);
|
||||
_points = new Vector3[(_columns + 1) * (_rows + 1)];
|
||||
for (int z = 0; z <= _rows; z++)
|
||||
for (int x = 0; x <= _columns; x++)
|
||||
_points[z * (_columns + 1) + x] = new Vector3((x - _columns * 0.5f) * d.Width, 0, (_rows * 0.5f - z) * d.Width);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Apply(EffectTask t, OriginalTaskClock clock, float dt)
|
||||
{
|
||||
base.Apply(t, clock, dt);
|
||||
if (_kind == "cylinder")
|
||||
{
|
||||
Scale.z = Scale.x;
|
||||
// The union at CreateTimeSlot is UV speed for cylinders, not
|
||||
// Z stretch. GameBox resets a positive V offset after one turn.
|
||||
if (TextureOffset > 1)
|
||||
TextureOffset = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Grid Z stretch shares CreateTimeSlot; YStretchSpeed is not
|
||||
// used by CEffGrid (height comes from its flap calculation).
|
||||
Scale.y = 1;
|
||||
}
|
||||
}
|
||||
|
||||
public override void Render(Camera camera)
|
||||
{
|
||||
_mesh.Clear();
|
||||
if (!Alive || !Visible)
|
||||
{
|
||||
_mesh.Upload();
|
||||
return;
|
||||
}
|
||||
var uv = Atlas(LocalTime);
|
||||
Quaternion rot = RawRotation(Rotation);
|
||||
Vector3 P(int index)
|
||||
{
|
||||
Vector3 p = _points[index];
|
||||
if (_kind == "grid")
|
||||
{
|
||||
float x = index % (_columns + 1), z = index / (_columns + 1);
|
||||
float sin = Mathf.Sin((LocalTime + x + 1) * Definition.BottomRadius + z + 1);
|
||||
float cos = Mathf.Cos((LocalTime + z + 1) * Definition.BottomRadius + x + 1);
|
||||
p.x += (sin - cos) * Definition.TopRadius;
|
||||
p.z += (cos + sin) * Definition.TopRadius;
|
||||
p.y += Mathf.Sin(LocalTime * Definition.TopRadiusIncreaseSpeed + x) * Definition.TextureRepeat;
|
||||
}
|
||||
return UnityPosition(Position + Orbit + rot * Vector3.Scale(p, Scale));
|
||||
}
|
||||
if (_kind == "cylinder")
|
||||
{
|
||||
float repeat = Definition.TextureRepeat;
|
||||
for (int i = 0; i < _columns; i++)
|
||||
{
|
||||
float u0 = uv.min.x + (uv.max.x - uv.min.x) * repeat * i / _columns;
|
||||
float u1 = uv.min.x + (uv.max.x - uv.min.x) * repeat * (i + 1) / _columns;
|
||||
_mesh.Quad(P(i * 2), P(i * 2 + 2), P(i * 2 + 3), P(i * 2 + 1),
|
||||
new Vector2(u0, uv.min.y + TextureOffset), new Vector2(u1, uv.max.y + TextureOffset), Tint);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int z = 0; z < _rows; z++)
|
||||
for (int x = 0; x < _columns; x++)
|
||||
{
|
||||
int i = z * (_columns + 1) + x;
|
||||
Vector2 a = Vector2.Lerp(uv.min, uv.max, 0);
|
||||
a.x = Mathf.Lerp(uv.min.x, uv.max.x, (float)x / _columns);
|
||||
a.y = Mathf.Lerp(uv.min.y, uv.max.y, (float)z / _rows);
|
||||
Vector2 b = new(Mathf.Lerp(uv.min.x, uv.max.x, (float)(x + 1) / _columns), Mathf.Lerp(uv.min.y, uv.max.y, (float)(z + 1) / _rows));
|
||||
_mesh.Quad(P(i), P(i + 1), P(i + _columns + 2), P(i + _columns + 1), a, b, Tint);
|
||||
}
|
||||
}
|
||||
_mesh.Upload();
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
_mesh.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b4096b3ce200a447ba269be4a95c0f5a
|
||||
@@ -0,0 +1,175 @@
|
||||
// ------------------------------------------------------------------------
|
||||
// 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 System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Core.DataReader.Pol;
|
||||
using Engine.Core.Abstraction;
|
||||
using Engine.Extensions;
|
||||
using UnityEngine.Rendering;
|
||||
using Core.DataReader.Data;
|
||||
using Engine.Core.Implementation;
|
||||
using Rendering.Material;
|
||||
using Rendering.Renderer;
|
||||
using UnityEngine;
|
||||
|
||||
internal sealed class OriginalModelNode : OriginalEffectNode
|
||||
{
|
||||
private const float ReferenceFramesPerSecond = 60f;
|
||||
private readonly CvdModelRenderer _model;
|
||||
private readonly GameMaterialManager _materials;
|
||||
private readonly Renderer[] _renderers;
|
||||
private float _animationStart;
|
||||
private float _opacity = 1;
|
||||
private readonly List<IMaterial[]> _polMaterials = new();
|
||||
private readonly List<Mesh> _meshes = new();
|
||||
private readonly List<Material> _opacityMaterials = new();
|
||||
private readonly MaterialPropertyBlock _properties = new();
|
||||
|
||||
public OriginalModelNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, OriginalEffectResources resources)
|
||||
: base(root, d, tasks, origin, birth)
|
||||
{
|
||||
// CEffModel ignores the flexeff tint/additive/depth flags: the model
|
||||
// owns those settings. SetBlend(ALPHA) overrides them only for fades.
|
||||
_materials = new GameMaterialManager(new UnityMaterialFactory(), false);
|
||||
try
|
||||
{
|
||||
if (d.TextureName.EndsWith(".cvd", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_model = root.AddComponent<CvdModelRenderer>();
|
||||
_model.Init(resources.Model(d.TextureName), resources.ModelTextureProvider(d.TextureName), _materials);
|
||||
}
|
||||
else if (d.TextureName.EndsWith(".pol", StringComparison.OrdinalIgnoreCase))
|
||||
RenderPol(root, d.TextureName, resources);
|
||||
else
|
||||
throw new NotSupportedException($"Unsupported original model {d.TextureName}");
|
||||
}
|
||||
catch
|
||||
{
|
||||
_model?.Dispose();
|
||||
foreach (Mesh mesh in _meshes)
|
||||
OriginalEffectResources.Destroy(mesh);
|
||||
foreach (IMaterial[] materials in _polMaterials)
|
||||
_materials.ReturnToPool(materials);
|
||||
_materials.Dispose();
|
||||
throw;
|
||||
}
|
||||
_renderers = root.GetComponentsInChildren<Renderer>();
|
||||
foreach (Transform child in root.GetComponentsInChildren<Transform>())
|
||||
child.gameObject.layer = root.layer;
|
||||
}
|
||||
|
||||
private void RenderPol(GameObject root, string path, OriginalEffectResources resources)
|
||||
{
|
||||
ITextureResourceProvider provider = resources.ModelTextureProvider(path);
|
||||
foreach (PolMesh source in resources.PolModel(path).Meshes)
|
||||
{
|
||||
Vector3[] positions = source.VertexInfo.GameBoxPositions.ToUnityPositions();
|
||||
foreach (PolTexture texture in source.Textures)
|
||||
{
|
||||
if (texture.GameBoxTriangles.Length == 0)
|
||||
continue;
|
||||
string[] names = texture.Material.TextureFileNames;
|
||||
int main = names.Length > 1 && !string.IsNullOrEmpty(names[1]) ? 1 : 0;
|
||||
ITexture2D Texture(int index) => string.IsNullOrEmpty(names[index])
|
||||
? new UnityTexture2D(Texture2D.whiteTexture) : provider.GetTexture(names[index]);
|
||||
IMaterial[] materials = _materials.CreateStandardMaterials(Rendering.RendererType.Pol,
|
||||
(names[main], Texture(main)), main == 1 ? (names[0], Texture(0)) : default,
|
||||
Core.Primitives.Color.White, texture.BlendFlag);
|
||||
_polMaterials.Add(materials);
|
||||
var mesh = new Mesh { name = "Original effect POL", indexFormat = IndexFormat.UInt32, hideFlags = HideFlags.DontSave };
|
||||
_meshes.Add(mesh);
|
||||
mesh.vertices = positions;
|
||||
mesh.uv = source.VertexInfo.Uvs[main].ToUnityVector2s();
|
||||
mesh.uv2 = source.VertexInfo.Uvs[0].ToUnityVector2s();
|
||||
mesh.triangles = texture.GameBoxTriangles.Reverse().ToArray();
|
||||
mesh.RecalculateBounds();
|
||||
var child = new GameObject("Original POL section") { hideFlags = HideFlags.DontSave, layer = root.layer };
|
||||
child.transform.SetParent(root.transform, false);
|
||||
child.AddComponent<MeshFilter>().sharedMesh = mesh;
|
||||
MeshRenderer renderer = child.AddComponent<MeshRenderer>();
|
||||
renderer.sharedMaterials = materials.Select(m => (Material)m.NativeObject).ToArray();
|
||||
renderer.shadowCastingMode = ShadowCastingMode.Off;
|
||||
renderer.receiveShadows = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void EnableOpacityOverride()
|
||||
{
|
||||
if (_opacityMaterials.Count > 0)
|
||||
return;
|
||||
foreach (Renderer renderer in _renderers)
|
||||
{
|
||||
if (renderer.sharedMaterial == null)
|
||||
continue;
|
||||
var material = new Material(renderer.sharedMaterial)
|
||||
{
|
||||
shader = Shader.Find("Pal3/Transparent"),
|
||||
hideFlags = HideFlags.DontSave
|
||||
};
|
||||
material.SetInt("_BlendSrcFactor", (int)BlendMode.SrcAlpha);
|
||||
material.SetInt("_BlendDstFactor", (int)BlendMode.OneMinusSrcAlpha);
|
||||
material.SetFloat("_Threshold", 2);
|
||||
material.renderQueue = (int)RenderQueue.Transparent;
|
||||
_opacityMaterials.Add(material);
|
||||
// Existing CVD/POL cutout + blend passes become a single alpha pass.
|
||||
renderer.sharedMaterials = new[] { material };
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Apply(EffectTask t, OriginalTaskClock clock, float dt)
|
||||
{
|
||||
if (clock.StartedNow)
|
||||
_animationStart = LocalTime;
|
||||
base.Apply(t, clock, dt);
|
||||
if (t.SpeedAlpha != 0)
|
||||
{
|
||||
EnableOpacityOverride();
|
||||
_opacity = Mathf.Clamp01(_opacity + t.SpeedAlpha * dt);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void ApplyRotationAndStretch(EffectTask t, float dt)
|
||||
{
|
||||
// CEffModel.cpp:238-245 adds these values once per update. Normalize
|
||||
// to our chosen 60 FPS compatibility reference, independently of
|
||||
// the display frame rate and the editor/seek integration step.
|
||||
base.ApplyRotationAndStretch(t, dt * ReferenceFramesPerSecond);
|
||||
}
|
||||
|
||||
public override void Render(Camera camera)
|
||||
{
|
||||
Root.transform.localPosition = UnityPosition(Position + Orbit);
|
||||
Root.transform.localRotation = UnityRotation(Rotation);
|
||||
Root.transform.localScale = Scale;
|
||||
_properties.SetColor("_TintColor", new Color(1, 1, 1, _opacity));
|
||||
foreach (Renderer renderer in _renderers)
|
||||
{
|
||||
renderer.enabled = Alive && Visible;
|
||||
if (_opacityMaterials.Count > 0)
|
||||
renderer.SetPropertyBlock(_properties);
|
||||
}
|
||||
if (Alive && Visible)
|
||||
_model?.SetCurrentTime(Mathf.Max(0, LocalTime - _animationStart));
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
_model?.Dispose();
|
||||
foreach (Mesh mesh in _meshes)
|
||||
OriginalEffectResources.Destroy(mesh);
|
||||
foreach (Material material in _opacityMaterials)
|
||||
OriginalEffectResources.Destroy(material);
|
||||
foreach (IMaterial[] materials in _polMaterials)
|
||||
_materials.ReturnToPool(materials);
|
||||
_materials.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 931441919a39d495fa8277a0dca473d0
|
||||
@@ -0,0 +1,279 @@
|
||||
// ------------------------------------------------------------------------
|
||||
// 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 Core.DataReader.Data;
|
||||
using Core.DataReader.Par;
|
||||
using Core.Primitives;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
|
||||
// sgpar's sampled curves and drag do not match Shuriken modules exactly.
|
||||
// Simulate those semantics in C#, and use the native particle renderer.
|
||||
// This is PAL3's CEffgbParticle -> ParticleEffect/particle.cpp path, not
|
||||
// gbengine9/physics/gbparteffect.cpp: the combat implementation scales both
|
||||
// scope and displacement and forces ONE/ONE blending regardless of BlendMode.
|
||||
internal sealed class OriginalParticleNode : OriginalEffectNode
|
||||
{
|
||||
private struct Unit
|
||||
{
|
||||
public Vector3 Position, Velocity;
|
||||
public float Age, Life, Size, Rotation, Direction;
|
||||
public int Row;
|
||||
public bool Alive;
|
||||
}
|
||||
|
||||
private sealed class Controller
|
||||
{
|
||||
public ParticleDescription Particle;
|
||||
public ParticleEmitter Emitter;
|
||||
public ParticleShapeFile Shape;
|
||||
public ParticleSystem System;
|
||||
public ParticleSystem.Particle[] Output;
|
||||
public Unit[] Units;
|
||||
public float CycleTime, Accumulator;
|
||||
public int Count;
|
||||
public bool Emitting = true;
|
||||
}
|
||||
|
||||
private readonly ParticleFile _file;
|
||||
private readonly Controller[] _controllers;
|
||||
private readonly System.Random _random;
|
||||
private float _spaceScale;
|
||||
private bool _loopEmission;
|
||||
|
||||
public override int QuadCount
|
||||
{
|
||||
get
|
||||
{
|
||||
int n = 0;
|
||||
foreach (Controller c in _controllers)
|
||||
n += c.Count;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
||||
public OriginalParticleNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth,
|
||||
OriginalEffectResources resources, uint seed, OriginalEffectOverrides edits) : base(root, d, tasks, origin, birth)
|
||||
{
|
||||
_random = new System.Random(unchecked((int)seed));
|
||||
_file = resources.Particle(d.ParticleFileName, edits);
|
||||
_spaceScale = d.InitSize;
|
||||
_controllers = new Controller[_file.Controllers.Length];
|
||||
for (int i = 0; i < _controllers.Length; i++)
|
||||
{
|
||||
ParticleController source = _file.Controllers[i];
|
||||
var c = new Controller { Particle = _file.Particles[source.ParticleIndex], Emitter = _file.Emitters[source.EmitterIndex] };
|
||||
int capacity = Mathf.Clamp(_file.Capacity, 1, 65536);
|
||||
c.Units = new Unit[capacity];
|
||||
c.Output = new ParticleSystem.Particle[capacity];
|
||||
var child = new GameObject(c.Particle.Name) { hideFlags = HideFlags.DontSave, layer = root.layer };
|
||||
child.transform.SetParent(root.transform, false);
|
||||
c.System = child.AddComponent<ParticleSystem>();
|
||||
c.System.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
|
||||
var main = c.System.main;
|
||||
main.playOnAwake = false;
|
||||
main.maxParticles = capacity;
|
||||
main.simulationSpace = ParticleSystemSimulationSpace.Local;
|
||||
main.gravityModifier = 0;
|
||||
main.startSpeed = 0;
|
||||
main.startLifetime = 10000;
|
||||
main.startSize = 1;
|
||||
main.cullingMode = ParticleSystemCullingMode.AlwaysSimulate;
|
||||
c.System.useAutoRandomSeed = false;
|
||||
c.System.randomSeed = seed + (uint)i;
|
||||
var emission = c.System.emission;
|
||||
emission.enabled = false;
|
||||
var shape = c.System.shape;
|
||||
shape.enabled = false;
|
||||
var renderer = c.System.GetComponent<ParticleSystemRenderer>();
|
||||
renderer.sharedMaterial = resources.Material(OriginalEffectResources.RelativeTo(d.ParticleFileName, c.Particle.Texture), true, false, 1);
|
||||
renderer.renderMode = ParticleSystemRenderMode.Billboard;
|
||||
renderer.alignment = ParticleSystemRenderSpace.View;
|
||||
renderer.minParticleSize = 0;
|
||||
renderer.maxParticleSize = 100;
|
||||
renderer.shadowCastingMode = ShadowCastingMode.Off;
|
||||
renderer.receiveShadows = false;
|
||||
renderer.sortMode = ParticleSystemSortMode.None;
|
||||
var atlas = c.System.textureSheetAnimation;
|
||||
atlas.enabled = true;
|
||||
atlas.numTilesX = c.Particle.Columns;
|
||||
atlas.numTilesY = c.Particle.Rows;
|
||||
atlas.animation = ParticleSystemAnimationType.WholeSheet;
|
||||
atlas.cycleCount = 1;
|
||||
atlas.frameOverTime = new ParticleSystem.MinMaxCurve(1, AnimationCurve.Linear(0, 0, 1, 1));
|
||||
// A stopped system can discard externally supplied particles in
|
||||
// editor preview. Keep it initialized and paused; C# owns time.
|
||||
c.System.Play(false);
|
||||
c.System.Pause(false);
|
||||
if (c.Emitter.Shape == 2)
|
||||
c.Shape = resources.Shape(OriginalEffectResources.RelativeTo(d.ParticleFileName, c.Emitter.ShapePath));
|
||||
_controllers[i] = c;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Apply(EffectTask t, OriginalTaskClock clock, float dt)
|
||||
{
|
||||
if (clock.StartedNow)
|
||||
_loopEmission = true;
|
||||
Position += new Vector3(t.SpeedX, t.SpeedY, t.SpeedZ) * dt;
|
||||
_spaceScale = Mathf.Max(0.001f, _spaceScale + t.XStretchSpeed * dt);
|
||||
Vector3 axis = new(t.CircleAxisX, t.CircleAxisY, t.CircleAxisZ);
|
||||
Orbit = OrbitPosition(axis, (LocalTime - clock.StartedAt) * t.CircleSpeed, t.CircleRadius);
|
||||
}
|
||||
|
||||
public override void Step(float time, float dt)
|
||||
{
|
||||
foreach (Controller c in _controllers)
|
||||
{
|
||||
ParticleEmitter e = c.Emitter;
|
||||
ParticleDescription p = c.Particle;
|
||||
float cycle = Mathf.Max(0.000001f, e.CycleMin - e.CycleMax);
|
||||
c.CycleTime += dt;
|
||||
// sgpar starts with one active emitter cycle. CEffgbParticle
|
||||
// updates it before the tasks, which control future looping;
|
||||
// disabling looping lets the current cycle finish normally.
|
||||
if (c.CycleTime > cycle)
|
||||
{
|
||||
c.Emitting = _loopEmission;
|
||||
if (_loopEmission)
|
||||
c.CycleTime = 0;
|
||||
}
|
||||
float phase = c.CycleTime / cycle;
|
||||
int lo = (int)(e.Emission.Evaluate(phase, 0) * e.SpeedMultiplier);
|
||||
int hi = (int)(e.Emission.Evaluate(phase, 1) * e.SpeedMultiplier);
|
||||
if (c.Emitting)
|
||||
{
|
||||
c.Accumulator += RandomRange(lo, hi) * dt;
|
||||
int number = Mathf.Clamp((int)c.Accumulator, 0, c.Units.Length);
|
||||
c.Accumulator -= number;
|
||||
for (int n = 0; n < number; n++)
|
||||
{
|
||||
int slot = Array.FindIndex(c.Units, u => !u.Alive);
|
||||
if (slot < 0)
|
||||
{
|
||||
if (_file.Overflow == 0)
|
||||
break;
|
||||
slot = _file.Overflow == 2 ? _random.Next(c.Units.Length) : Oldest(c.Units);
|
||||
}
|
||||
c.Units[slot] = Spawn(c, phase);
|
||||
}
|
||||
}
|
||||
c.Count = 0;
|
||||
for (int i = 0; i < c.Units.Length; i++)
|
||||
{
|
||||
ref Unit u = ref c.Units[i];
|
||||
if (!u.Alive)
|
||||
continue;
|
||||
u.Age += dt;
|
||||
if (u.Age > u.Life)
|
||||
{
|
||||
u.Alive = false;
|
||||
continue;
|
||||
}
|
||||
float t = u.Age / u.Life;
|
||||
if (u.Velocity.magnitude > p.NoResistanceSpeed)
|
||||
{
|
||||
Vector3 drag = u.Velocity * p.Resistance;
|
||||
if (p.SizeResistancePower != 0)
|
||||
drag += u.Velocity.normalized * (u.Size * p.Resistance);
|
||||
u.Velocity -= drag * dt;
|
||||
}
|
||||
u.Size = p.Size.Evaluate(t);
|
||||
u.Rotation = (u.Rotation + (p.Rotation.Evaluate(t) + RandomRange(p.RotationStart, p.RotationEnd)) * dt) * u.Direction;
|
||||
Vector3 offset = u.Velocity * dt;
|
||||
offset.y -= p.Gravity * dt * dt / 2;
|
||||
u.Velocity.y -= p.Gravity * dt;
|
||||
u.Position += offset * _spaceScale;
|
||||
c.Count++;
|
||||
}
|
||||
}
|
||||
base.Step(time, dt);
|
||||
if (!Alive)
|
||||
_loopEmission = false;
|
||||
foreach (Controller c in _controllers)
|
||||
Alive |= c.Count > 0;
|
||||
}
|
||||
|
||||
private Unit Spawn(Controller c, float t)
|
||||
{
|
||||
ParticleEmitter e = c.Emitter;
|
||||
ParticleDescription p = c.Particle;
|
||||
Vector3 direction = new(e.Direction.Evaluate(t, 0), e.Direction.Evaluate(t, 1), e.Direction.Evaluate(t, 2));
|
||||
Vector3 scope = Raw(e.Scope) * _spaceScale;
|
||||
Vector3 velocity = direction * RandomRange(e.RandomVelocity.Evaluate(t, 0), e.RandomVelocity.Evaluate(t, 1))
|
||||
+ new Vector3(RandomRange(-scope.x, scope.x), RandomRange(-scope.y, scope.y), RandomRange(-scope.z, scope.z));
|
||||
Vector3 position;
|
||||
if (e.Shape == 2)
|
||||
position = Raw(c.Shape.Points[_random.Next(c.Shape.Points.Length)]);
|
||||
else if (e.Shape == 1)
|
||||
position = new Vector3(RandomRange(-100, 100), RandomRange(-100, 100), RandomRange(-100, 100)).normalized
|
||||
* RandomRange(0, _random.Next(2) == 0 ? e.Hotspot : e.Hotspot + e.Falloff);
|
||||
else
|
||||
position = new Vector3(RandomRange(e.BoxMin.X, e.BoxMax.X), RandomRange(e.BoxMin.Y, e.BoxMax.Y), RandomRange(e.BoxMin.Z, e.BoxMax.Z));
|
||||
position = (position + Raw(e.Position)) * _spaceScale;
|
||||
return new Unit
|
||||
{
|
||||
Alive = true,
|
||||
Position = position,
|
||||
Velocity = velocity,
|
||||
Direction = p.RandomRotationDirection && _random.Next(2) == 0 ? -1 : 1,
|
||||
Life = Mathf.Max(0.000001f, RandomRange(e.Life.Evaluate(t, 0), e.Life.Evaluate(t, 1))),
|
||||
Size = p.Size.Evaluate(0),
|
||||
Row = _random.Next(p.Rows)
|
||||
};
|
||||
}
|
||||
|
||||
public override void Render(Camera camera)
|
||||
{
|
||||
foreach (Controller c in _controllers)
|
||||
{
|
||||
int n = 0;
|
||||
ParticleDescription p = c.Particle;
|
||||
for (int i = 0; i < c.Units.Length; i++)
|
||||
{
|
||||
Unit u = c.Units[i];
|
||||
if (!u.Alive)
|
||||
continue;
|
||||
float phase = u.Age / u.Life;
|
||||
int frame = Mathf.Min(p.Columns - 1, (int)(phase * p.Columns));
|
||||
// Native texture-sheet lookup uses normalized remaining life.
|
||||
float atlasLife = (u.Row * p.Columns + frame + 0.25f) / (p.Rows * p.Columns);
|
||||
var color = new UnityEngine.Color(p.Color.Evaluate(phase, 0) / 255, p.Color.Evaluate(phase, 1) / 255,
|
||||
p.Color.Evaluate(phase, 2) / 255, p.Alpha.Evaluate(phase));
|
||||
// CEffgbParticle translates the view for the entire effect,
|
||||
// even for sgpar's world-space mode. Task motion therefore
|
||||
// moves existing particles as well as newly emitted ones.
|
||||
c.Output[n++] = new ParticleSystem.Particle
|
||||
{
|
||||
position = UnityPosition(u.Position + Position + Orbit),
|
||||
startSize = Mathf.Abs(u.Size * _spaceScale / 20),
|
||||
rotation = -u.Rotation,
|
||||
startColor = color,
|
||||
startLifetime = 1,
|
||||
remainingLifetime = 1 - atlasLife,
|
||||
randomSeed = (uint)(i + 1)
|
||||
};
|
||||
}
|
||||
c.System.SetParticles(c.Output, n);
|
||||
}
|
||||
}
|
||||
|
||||
private float RandomRange(float a, float b) => a + (b - a) * ((float)_random.Next(1, 10001) / 10000);
|
||||
|
||||
private static Vector3 Raw(GameBoxVector3 v) => new(v.X, v.Y, v.Z);
|
||||
|
||||
private static int Oldest(Unit[] units)
|
||||
{
|
||||
int result = 0;
|
||||
for (int i = 1; i < units.Length; i++)
|
||||
if (units[i].Age > units[result].Age)
|
||||
result = i;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 13f42c5931db146b8a60320470832551
|
||||
Loaded 100 of 166 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user