Compare commits

...
86 Commits
Author SHA1 Message Date
Jiaqi Liu 5944c664f1 Update QualitySettings.asset 2022-11-07 02:45:53 -08:00
Jiaqi Liu 72f77ff1a7 v0.31 2022-11-07 02:37:22 -08:00
Jiaqi Liu 41efbdce8e Use CascadedShadowMaps for tier 3 mobile devices 2022-11-07 02:36:42 -08:00
Jackie Liu d751d5ea2a Hide collectable and chests 2022-11-07 02:34:03 -08:00
Jackie Liu 12ef307fe6 VFX WIP 2022-11-07 02:09:22 -08:00
Jackie Liu bc672d6179 Fix CVD normal issue 2022-11-06 05:58:00 -08:00
Jackie Liu fbadf6766e Add GamePad deadzone processor & code refactoring 2022-11-06 04:42:47 -08:00
Jiaqi Liu 41502ddefb Lighting tweaks 2022-11-03 06:58:44 -07:00
Jackie Liu 61ca35b1b8 Code refactoring 2022-11-01 19:05:05 -07:00
Jiaqi Liu cbb4d5e575 Bug fixes 2022-11-01 05:12:40 -07:00
Jiaqi Liu b37ac428d2 Minor fixes 2022-11-01 01:13:40 -07:00
Jiaqi Liu f9d17a9896 Disable automatic graphics API on Android 2022-11-01 01:00:29 -07:00
Jackie Liu 65d4fefd6f Update QualitySettings.asset 2022-10-31 21:16:12 -07:00
Jackie Liu 5e746c7922 v0.30 2022-10-31 21:06:31 -07:00
Jackie Liu 3c31cb1787 Lighting tweaks 2022-10-31 20:30:16 -07:00
Jackie Liu b0ea2f8638 Effect sprite rendering issue fixes
Also fixed portal base sprite rotation issue
2022-10-31 05:06:44 -07:00
Jackie Liu e38ffc9a40 Distortion code refactoring 2022-10-31 02:56:04 -07:00
Jiaqi Liu 96e2d151f9 Update QualitySettings.asset 2022-10-31 02:46:49 -07:00
yunyouandJackie Liu 23fa70496b 使用官方 PostProcessing ,扩展出来了一个 Distortion 的后处理 (#9)
* +extend PostProcessing , integrate Water wave Distortion into the game. Test it with "EffectSetScreenEffect 0"

Co-authored-by: Jackie Liu <jackil@microsoft.com>
2022-10-31 16:54:42 +08:00
Jackie Liu b3f67d3683 Lighting tweaks 2022-10-31 01:32:49 -07:00
Jackie Liu 84e44d7eec Lighting tweaks 2022-10-30 01:38:27 -07:00
Jackie Liu 661d2ce1c0 Nav mesh fixes 2022-10-30 00:58:46 -07:00
Jackie Liu be695cc353 Lighting tweaks 2022-10-29 19:56:27 -07:00
Jackie Liu 6aa8da32ea Code refactoring and bug fixes 2022-10-29 19:01:45 -07:00
Jackie Liu 2de4bce9e1 Tweak camera nearClipPlane value 2022-10-28 19:07:08 -07:00
Jackie Liu 56ec4d81ad Fix poly and cvd normal issues 2022-10-28 18:49:40 -07:00
Jackie Liu 261ad74a74 Fix mv3 normal issue by splitting the vertices & fix nav mesh facing issue 2022-10-28 17:45:04 -07:00
Jiaqi Liu 654ade106e Update screenshots 2022-10-28 06:01:59 -07:00
Jiaqi Liu 15970562d7 Bump Unity version 2022-10-27 22:31:47 -07:00
Jackie Liu c3fe8198d4 Fix build error 2022-10-27 11:09:10 -07:00
Jackie Liu 593e915dcd Calculate MV3 normals in Mv3FileReader 2022-10-27 01:58:02 -07:00
Jackie Liu 6d6f195aad Enable Ambient Occlusion on desktop devices 2022-10-26 19:03:46 -07:00
Jackie Liu 17814972f4 Tweak fire effect light source location 2022-10-26 18:39:47 -07:00
Jackie Liu a898c69b79 Fix mv3 normals with code refactoring 2022-10-26 18:24:58 -07:00
Jackie Liu 4d473bf69b Reduce shadowResolution 2022-10-26 01:08:23 -07:00
Jackie Liu 9eb091ead6 Temp workaround for mv3 normals 2022-10-26 00:07:52 -07:00
Jackie Liu 49f25b255e Add ToonMaterialFactory, temp fix for normals 2022-10-26 00:07:05 -07:00
Jackie Liu 820c3f1795 Code refactoring 2022-10-25 19:16:25 -07:00
Jackie Liu dac1505886 Move shaders to resource folder 2022-10-25 10:56:50 -07:00
Jackie Liu 2f12c317c4 Lighting tweaks 2022-10-25 00:58:25 -07:00
Jackie Liu 421aeb4c3f Minor tweaks 2022-10-25 00:41:18 -07:00
Jackie Liu 7dfdd4396f All about normals 2022-10-24 18:55:08 -07:00
Jackie Liu 4cf4890693 Light color tweaks 2022-10-24 04:35:13 -07:00
Jiaqi Liu dbeef96411 Update QualitySettings.asset 2022-10-24 04:14:44 -07:00
Jiaqi Liu c47f5b8edb Update SettingsManager.cs 2022-10-24 03:31:05 -07:00
Jackie Liu 173c95c70d Typo fix 2022-10-24 03:20:20 -07:00
Jiaqi Liu 993b5e7653 Experimental (#8)
* Experimental feature
2022-10-24 18:12:03 +08:00
Jiaqi Liu bbeca7a6c6 PostProcessManager code refactoring 2022-10-22 23:19:01 -07:00
Jackie Liu 845f7e8fd5 Fix fire sprite and implement CPK extractor feature in GameResourceViewer 2022-10-21 22:14:33 -07:00
Jackie Liu f2fe362d53 Add bloom effect for VFX with code refactoring 2022-10-21 20:44:19 -07:00
Jackie Liu 53efd23d0f Fix default weapon model for ZiXuan 2022-10-21 01:26:59 -07:00
Jackie Liu 8730c457c2 v0.29 2022-10-21 00:52:32 -07:00
Jackie Liu 1e2e080657 Implement portal ray effect 2022-10-21 00:50:51 -07:00
Jackie Liu a14be2670b VFX WIP: Adding bridge effect 2022-10-21 00:08:50 -07:00
Jackie Liu 766fe2c430 VFX WIP 2022-10-20 02:18:16 -07:00
Jiaqi Liu f7c0aa8e71 Delete 262.prefab.meta 2022-10-19 21:18:52 -07:00
Jackie Liu 18563a5063 Preload VFX prefab 2022-10-19 18:52:40 -07:00
Jackie Liu 5a12990ce1 VFX WIP 2022-10-19 00:27:21 -07:00
Jackie Liu 4c31d56b78 Code refactoring for VFX gameobject 2022-10-18 19:01:33 -07:00
Jackie Liu 9de0e3f9cb Update gitignore 2022-10-18 18:47:21 -07:00
Jackie Liu 8ff5685ed8 VFX init 2022-10-18 18:16:11 -07:00
Jiaqi Liu 4ac04f9e06 Added missing shaders in build bundle 2022-10-17 20:10:38 -07:00
Jiaqi Liu f7c993ef22 Minor tweaks and fixes 2022-10-17 10:15:23 -07:00
Jackie Liu ba68240d77 Minor tweaks 2022-10-17 03:06:59 -07:00
Jackie Liu 76f1b1f551 Fix quaternion calculation for the light source 2022-10-17 02:17:06 -07:00
Jackie Liu dc8b9f6423 Minor fix 2022-10-16 22:40:40 -07:00
Jackie Liu 94b26e15c3 Read Lgt file and create light source objects in editor 2022-10-16 22:27:22 -07:00
yunyouandJiaqi Liu 7ff9146b5e +water using indie material. apply water shadow texture on it (#7)
* +water using indie material. apply water shadow texture on it

* +modify Pal3Water.shader default blend parameter

* Uses first pixel's alpha as water surface opacity

Uses first pixel's alpha as water surface opacity and code refactoring

* Minor tweaks with exposure amount

* Remove empty line

Co-authored-by: Jiaqi Liu <jackil@microsoft.com>
2022-10-16 12:12:57 -07:00
Jackie Liu 2e5421146b EffectDefinition WIP 2022-10-15 17:38:18 -07:00
Jiaqi Liu 780041ec27 Merge pull request #6 from yunyou730/render_order
* Introduce MaterialFactory to manage the creation of materials.
* Fixed semi-transparent object and actor rendering order issue by implementing corresponding shaders with correct render pass.
* Proper implementation of PAL3 sprite shader.
2022-10-15 13:28:43 -07:00
Jackie Liu 8d13753246 Format refactorings 2022-10-15 13:25:38 -07:00
Jackie Liu 1a865a32c0 Code refactoring 2022-10-15 13:03:12 -07:00
Jackie Liu 59d7af002b Fixed a bug where PAL3A portal effect is not rendered correctly 2022-10-15 12:45:18 -07:00
Jackie Liu 9d62fc637a Code refactoring 2022-10-15 12:13:29 -07:00
yunyou da132bdf91 +clean material code 2022-10-15 23:57:00 +08:00
yunyou 0ca80340bc + sync comment with code 2022-10-15 23:43:14 +08:00
yunyou 93228511c3 +fix BlendFlag = 2, additive blend performance issue 2022-10-15 23:33:49 +08:00
miaoyunlong 63b5ca8393 +fix water not perform uv anim issue. 2022-10-15 16:08:29 +08:00
miaoyunlong 9003dbe3fc +3 shaders add _TintColor back (Pal3_Opaque, Pal3_Transparent, Pal3_TransparentOpaquePart) 2022-10-15 14:55:40 +08:00
Jackie Liu d8181e8dd8 Update Mv3ModelRenderer.cs 2022-10-14 20:53:31 -07:00
miaoyunlong 60519b39ef +调整渲染顺序为:Opaque -> SkyBox -> Transparent. 半透明物体会拆成 Opaque 和 Transparent 两部分绘制 2022-10-14 03:26:12 +08:00
miaoyunlong 23d3809cb7 +modify paremters 2022-10-13 22:47:07 +08:00
Jackie Liu 6622b3737c Should only record camera last transform when in gameplay state 2022-10-12 20:45:43 -07:00
miaoyunlong e00eb972a2 +fix transparent material alpha color bug 2022-10-13 01:51:25 +08:00
miaoyunlong e71a244ca6 +fix render order issue 2022-10-13 01:14:42 +08:00
Jiaqi Liu 3b6730b60a Fixed issue with Virtual Joystick UI not showing on some of the Android devices 2022-10-10 06:42:24 -07:00
133 changed files with 3240 additions and 840 deletions

No files matched your search

+14
View File
@@ -70,3 +70,17 @@ 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/
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0b0b27c9e5e4d2e4fbc9b6584f828f7b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
File renamed without changes.
@@ -0,0 +1,54 @@
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
/*
reference: https://www.shadertoy.com/view/MsKXDh
*/
Shader "Pal3/PostEffectDistortion"
{
Properties
{
_TimeScale ("Time Scale",float) = 4.0
_XFactor ("X Factor",float) = 15.0
_YFactor("Y Factor",float) = 10.0
}
HLSLINCLUDE
#include "Packages/com.unity.postprocessing/PostProcessing/Shaders/StdLib.hlsl"
TEXTURE2D_SAMPLER2D(_MainTex, sampler_MainTex);
float _TimeScale;
float _XFactor;
float _YFactor;
float4 Frag(VaryingsDefault i) : SV_Target
{
float2 uv = i.texcoord;
const float time = _Time.y;
uv.x += sin(uv.y * _XFactor + time * _TimeScale) / 400.0;
uv.y += cos(uv.x * _YFactor + time * _TimeScale) / 450.0;
uv.x += sin((uv.y+uv.x) * _XFactor + time * _TimeScale) / (180.0 + (_TimeScale * sin(time)));
uv.y += cos((uv.y+uv.x) * _YFactor + time * _TimeScale) / (200.0 + (_TimeScale * sin(time)));
float4 col = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex,uv);
return col;
}
ENDHLSL
SubShader
{
Cull Off ZWrite Off ZTest Always
Pass
{
HLSLPROGRAM
#pragma vertex VertDefault
#pragma fragment Frag
ENDHLSL
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 0b8bcccc572f924448668c94cfa547b4
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -44,6 +44,105 @@ MonoBehaviour:
opacity:
overrideState: 0
value: 1
--- !u!114 &-8365138130595697379
MonoBehaviour:
m_ObjectHideFlags: 3
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: bb4ad18ac69b12845a429aba13929a07, type: 3}
m_Name: Distortion
m_EditorClassIdentifier:
active: 0
enabled:
overrideState: 1
value: 1
timeScale:
overrideState: 0
value: 4
xFactor:
overrideState: 0
value: 15
yFactor:
overrideState: 0
value: 10
--- !u!114 &-806185241644601601
MonoBehaviour:
m_ObjectHideFlags: 3
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: bb4ad18ac69b12845a429aba13929a07, type: 3}
m_Name: Distortion
m_EditorClassIdentifier:
active: 1
enabled:
overrideState: 1
value: 1
timeScale:
overrideState: 0
value: 4
xFactor:
overrideState: 0
value: 15
yFactor:
overrideState: 0
value: 10
--- !u!114 &-804113543285745465
MonoBehaviour:
m_ObjectHideFlags: 3
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: c1cb7e9e120078f43bce4f0b1be547a7, type: 3}
m_Name: AmbientOcclusion
m_EditorClassIdentifier:
active: 0
enabled:
overrideState: 1
value: 1
mode:
overrideState: 1
value: 1
intensity:
overrideState: 1
value: 0.25
color:
overrideState: 0
value: {r: 0, g: 0, b: 0, a: 1}
ambientOnly:
overrideState: 0
value: 1
noiseFilterTolerance:
overrideState: 0
value: 0
blurTolerance:
overrideState: 0
value: -4.6
upsampleTolerance:
overrideState: 0
value: -12
thicknessModifier:
overrideState: 0
value: 1
directLightingStrength:
overrideState: 0
value: 0
radius:
overrideState: 0
value: 0.25
quality:
overrideState: 0
value: 2
--- !u!114 &-118557119588518591
MonoBehaviour:
m_ObjectHideFlags: 3
@@ -1370,3 +1469,78 @@ MonoBehaviour:
settings:
- {fileID: -118557119588518591}
- {fileID: -8887095760420704611}
- {fileID: 455792505896753558}
- {fileID: -804113543285745465}
- {fileID: -8365138130595697379}
--- !u!114 &455792505896753558
MonoBehaviour:
m_ObjectHideFlags: 3
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 48a79b01ea5641d4aa6daa2e23605641, type: 3}
m_Name: Bloom
m_EditorClassIdentifier:
active: 0
enabled:
overrideState: 1
value: 1
intensity:
overrideState: 1
value: 5
threshold:
overrideState: 1
value: 1.3
softKnee:
overrideState: 1
value: 0.5
clamp:
overrideState: 0
value: 65472
diffusion:
overrideState: 0
value: 7
anamorphicRatio:
overrideState: 0
value: 0
color:
overrideState: 0
value: {r: 1, g: 1, b: 1, a: 1}
fastMode:
overrideState: 1
value: 1
dirtTexture:
overrideState: 0
value: {fileID: 0}
defaultState: 1
dirtIntensity:
overrideState: 0
value: 0
--- !u!114 &954549172052332416
MonoBehaviour:
m_ObjectHideFlags: 3
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: bb4ad18ac69b12845a429aba13929a07, type: 3}
m_Name: Distortion
m_EditorClassIdentifier:
active: 0
enabled:
overrideState: 1
value: 1
timeScale:
overrideState: 0
value: 4
xFactor:
overrideState: 0
value: 15
yFactor:
overrideState: 0
value: 10
+5 -5
View File
@@ -220,7 +220,7 @@ Camera:
m_Depth: -1
m_CullingMask:
serializedVersion: 2
m_Bits: 55
m_Bits: 63
m_RenderingPath: -1
m_TargetTexture: {fileID: 0}
m_TargetDisplay: 0
@@ -343,7 +343,7 @@ MonoBehaviour:
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 311849590}
m_Enabled: 0
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 948f4100a11a5c24981795d21301da5c, type: 3}
m_Name:
@@ -351,7 +351,7 @@ MonoBehaviour:
volumeTrigger: {fileID: 311849593}
volumeLayer:
serializedVersion: 2
m_Bits: 55
m_Bits: 136
stopNaNPropagation: 0
finalBlitToCameraTarget: 0
antialiasingMode: 0
@@ -363,7 +363,7 @@ MonoBehaviour:
subpixelMorphologicalAntialiasing:
quality: 2
fastApproximateAntialiasing:
fastMode: 0
fastMode: 1
keepAlpha: 0
fog:
enabled: 1
@@ -2755,7 +2755,7 @@ GameObject:
m_Component:
- component: {fileID: 5491488055271105370}
- component: {fileID: 8346885185333560231}
m_Layer: 0
m_Layer: 3
m_Name: PostProcessVolume
m_TagString: Untagged
m_Icon: {fileID: 0}
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 2eaeb845461401e488e4640caf779ddf
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: b93923849ec63ad4ea52f79bf5bc9cb6
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,45 @@
因为当前特效的实现方式使用了第三方插件和素材,所以此文件夹内的所有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 => 蓝龙葵变红龙葵的特效
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 815b64a4a03e7b949bd85e1e5c19deb3
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a637ebcead3359c4f849f936d41707ee
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,67 @@
因为当前特效的实现方式使用了第三方插件和素材,所以此文件夹内的所有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 => 王蓬絮对南宫煌施法特效
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: f1d950c46b3119043a1919074fdc27c5
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 4f33d244048b1054a8753633da7ffe28
guid: fcd2231fc0b299247b47f42991d73ab5
folderAsset: yes
DefaultImporter:
externalObjects: {}
@@ -10,14 +10,16 @@ Shader "Pal3/Dev"
_MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
}
SubShader {
Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" }
SubShader
{
Tags { "Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "Transparent" }
LOD 100
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha
Pass {
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
@@ -63,4 +65,4 @@ Shader "Pal3/Dev"
ENDCG
}
}
}
}
@@ -0,0 +1,81 @@
Shader "Pal3/Opaque"
{
Properties
{
_MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
_TintColor ("Tint color", Color) = (1.0, 1.0, 1.0, 1.0)
_HasShadowTex ("Has Shadow Texture", Range(0, 1)) = 0.0
_ShadowTex ("Shadow Texture", 2D) = "white" {}
_Exposure("Exposure Amount", Range(0.1, 1.0)) = 0.4
}
SubShader
{
Lighting Off
Tags { "QUEUE" = "Geometry" }
Pass
{
Tags{ "Qeueue" = "Geometry" }
Blend Off
ZWrite On
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 2.0
#include "UnityCG.cginc"
struct appdata_t
{
float4 vertex : POSITION;
float2 texcoord : TEXCOORD0;
float2 shadowcoord : TEXCOORD1;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct v2f
{
float4 vertex : SV_POSITION;
float2 texcoord : TEXCOORD0;
float2 shadowcoord : TEXCOORD1;
UNITY_VERTEX_OUTPUT_STEREO
};
sampler2D _MainTex;
float4 _MainTex_ST;
float4 _TintColor;
float _HasShadowTex;
sampler2D _ShadowTex;
float4 _ShadowTex_ST;
float _Exposure;
v2f vert(appdata_t v)
{
v2f o;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.vertex = UnityObjectToClipPos(v.vertex);
o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);
o.shadowcoord = TRANSFORM_TEX(v.shadowcoord, _ShadowTex);
return o;
}
half4 frag(v2f i) : SV_Target
{
half4 color = tex2D(_MainTex, i.texcoord);
if(_HasShadowTex > 0.5f)
{
color *= tex2D(_ShadowTex, i.shadowcoord) / (1 - _Exposure);
}
color *= _TintColor;
return color;
}
ENDCG
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: a83b1b6f4822140d58c7bad4e3b39932
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,55 @@
Shader "Pal3/Sprite"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
Tags { "Queue" = "Transparent" }
LOD 100
Pass
{
Blend SrcAlpha One
ZWrite Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);
col.a = 1.0f; // force alpha to 1 to avoid transparency
return col;
}
ENDCG
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 6122fb5a4bad8433982c0407309f8dbf
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -1,34 +1,38 @@
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
Shader "Pal3/Standard"
Shader "Pal3/Transparent"
{
Properties
{
_MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
_ShadowTex ("Shadow map (RGB)", 2D) = "white" {}
_Cutoff ("Alpha cutoff", Range(0,1)) = 0.0
_Exposure("Exposure Amount", Range(0.1,1.0)) = 0.4
_IsOpaque("Is Material Opaque", Range(0,1)) = 1.0
_TintColor ("Tint color", Color) = (1.0, 1.0, 1.0, 1.0)
_Threshold ("Transparent Threshold", Range(0, 1)) = 1.0
_HasShadowTex ("Has Shadow Texture", Range(0, 1)) = 0.0
_ShadowTex ("Shadow Texture", 2D) = "white" {}
_Exposure("Exposure Amount", Range(0.1, 1.0)) = 0.4
[Enum(UnityEngine.Rendering.BlendMode)]
_BlendSrcFactor("Source Blend Factor", int) = 5 // BlendMode.SrcAlpha as Default
[Enum(UnityEngine.Rendering.BlendMode)]
_BlendDstFactor("Dest Blend Factor", int) = 10 // BlendMode.OneMinusSrcAlpha as Default
}
SubShader
{
Tags { "Queue"="Geometry" "IgnoreProjector"="True" "RenderType"="TransparentCutout" }
LOD 100
Lighting Off
Blend SrcAlpha OneMinusSrcAlpha
Tags { "Queue" = "Transparent" }
// Pass 2 ,transparent part
Pass
{
Blend [_BlendSrcFactor] [_BlendDstFactor]
ZWrite Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 2.0
#pragma multi_compile_fog
#include "UnityCG.cginc"
struct appdata_t
@@ -44,18 +48,21 @@ Shader "Pal3/Standard"
float4 vertex : SV_POSITION;
float2 texcoord : TEXCOORD0;
float2 shadowcoord : TEXCOORD1;
UNITY_FOG_COORDS(2)
UNITY_VERTEX_OUTPUT_STEREO
};
sampler2D _MainTex;
float4 _MainTex_ST;
float _Threshold;
float _HasShadowTex;
sampler2D _ShadowTex;
float4 _ShadowTex_ST;
fixed _Cutoff;
float _Exposure;
float _IsOpaque;
float4 _TintColor;
v2f vert(appdata_t v)
{
v2f o;
@@ -64,32 +71,24 @@ Shader "Pal3/Standard"
o.vertex = UnityObjectToClipPos(v.vertex);
o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);
o.shadowcoord = TRANSFORM_TEX(v.shadowcoord, _ShadowTex);
UNITY_TRANSFER_FOG(o, o.vertex);
return o;
}
half4 frag(v2f i) : SV_Target
{
half4 color = tex2D(_MainTex, i.texcoord);
const half alpha = color.a;
// Cutout
clip(color.a - _Cutoff);
// Shadow
color *= tex2D(_ShadowTex, i.shadowcoord) / (1 - _Exposure);
// Preserve alpha or not
if (_IsOpaque == 1.0)
const float alpha = color.a;
if(color.a >= _Threshold)
{
color.a = 1.0;
discard;
}
else
if(_HasShadowTex > 0.5f)
{
color *= tex2D(_ShadowTex, i.shadowcoord) / (1 - _Exposure);
color.a = alpha;
}
//UNITY_APPLY_FOG(i.fogCoord, color);
color *= _TintColor;
return color;
}
ENDCG
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 9a73f8d5b84814e63a97995e839fdabb
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -1,32 +1,31 @@
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
Shader "Pal3/StandardNoShadow"
Shader "Pal3/TransparentOpaquePart"
{
Properties
{
_MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
_Cutoff ("Alpha cutoff", Range(0,1)) = 0.0
_TintColor ("Tint color", Color) = (1.0, 1.0, 1.0, 1.0)
_IsOpaque("Is Material Opaque", Range(0,1)) = 1.0
_Threshold ("Transparent Threshold", Range(0, 1)) = 1.0
_HasShadowTex ("Has Shadow Texture", Range(0, 1)) = 0.0
_ShadowTex ("Shadow Texture", 2D) = "white" {}
_Exposure("Exposure Amount", Range(0.1, 1.0)) = 0.4
}
SubShader
{
Tags { "Queue"="Geometry" "IgnoreProjector"="True" "RenderType"="TransparentCutout" }
LOD 100
Lighting Off
Blend SrcAlpha OneMinusSrcAlpha
Tags { "Qeueue" = "Geometry" }
// pass 1 , opaque part
Pass
{
Blend Off
ZWrite On
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 2.0
#pragma multi_compile_fog
#include "UnityCG.cginc"
@@ -34,6 +33,7 @@ Shader "Pal3/StandardNoShadow"
{
float4 vertex : POSITION;
float2 texcoord : TEXCOORD0;
float2 shadowcoord : TEXCOORD1;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
@@ -41,15 +41,21 @@ Shader "Pal3/StandardNoShadow"
{
float4 vertex : SV_POSITION;
float2 texcoord : TEXCOORD0;
UNITY_FOG_COORDS(1)
float2 shadowcoord : TEXCOORD1;
UNITY_VERTEX_OUTPUT_STEREO
};
sampler2D _MainTex;
float4 _MainTex_ST;
fixed _Cutoff;
half4 _TintColor;
float _IsOpaque;
float _Threshold;
float _HasShadowTex;
sampler2D _ShadowTex;
float4 _ShadowTex_ST;
float _Exposure;
float4 _TintColor;
v2f vert(appdata_t v)
{
@@ -58,32 +64,21 @@ Shader "Pal3/StandardNoShadow"
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.vertex = UnityObjectToClipPos(v.vertex);
o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);
UNITY_TRANSFER_FOG(o, o.vertex);
o.shadowcoord = TRANSFORM_TEX(v.shadowcoord, _ShadowTex);
return o;
}
half4 frag(v2f i) : SV_Target
{
half4 color = tex2D(_MainTex, i.texcoord);
const half alpha = color.a;
// Cutout
clip(color.a - _Cutoff);
// Tint color
color *= _TintColor;
// Preserve alpha or not
if (_IsOpaque == 1.0)
{
color.a = 1.0;
}
else
{
color.a = alpha;
}
clip(color.a - _Threshold);
//UNITY_APPLY_FOG(i.fogCoord, color);
if(_HasShadowTex > 0.5f)
{
color *= tex2D(_ShadowTex, i.shadowcoord) / (1 - _Exposure);
}
color *= _TintColor;
return color;
}
ENDCG
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 784c49f60e0c64f6595ed503bd3a3a69
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:
+91
View File
@@ -0,0 +1,91 @@
Shader "Pal3/Water"
{
Properties
{
// main texture
_MainTex ("Main texture", 2D) = "white" {}
// alpha value
_Alpha ("Alpha",Range(0, 1)) = 0.5
_Exposure("Exposure Amount", Range(0.1, 1.0)) = 0.3
// pre baked shadow texture
_ShadowTex ("Shadow texture", 2D) = "white" {}
_HasShadowTex ("Has Shadow Texture", Range(0, 1)) = 0.0
[Enum(UnityEngine.Rendering.BlendMode)]
_BlendSrcFactor("Source Blend Factor", int) = 5 // BlendMode.SrcAlpha as Default
[Enum(UnityEngine.Rendering.BlendMode)]
_BlendDstFactor("Dest Blend Factor", int) = 10 // BlendMode.OneMinusSrcAlpha as Default
}
SubShader
{
Lighting Off
Tags { "QUEUE" = "Transparent-1" } // -1 to fix sorting order issue with semi-transparent trees etc.
Pass
{
Blend [_BlendSrcFactor] [_BlendDstFactor]
ZWrite Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 2.0
#include "UnityCG.cginc"
struct appdata_t
{
float4 vertex : POSITION;
float2 texcoord : TEXCOORD0;
float2 texcoord2 : TEXCOORD1;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct v2f
{
float4 vertex : SV_POSITION;
float2 texcoord : TEXCOORD0;
float2 texcoord2 : TEXCOORD1;
UNITY_VERTEX_OUTPUT_STEREO
};
sampler2D _MainTex;
float4 _MainTex_ST;
float _Alpha;
float _Exposure;
float _HasShadowTex;
sampler2D _ShadowTex;
float4 _ShadowTex_ST;
v2f vert(appdata_t v)
{
v2f o;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.vertex = UnityObjectToClipPos(v.vertex);
o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);
o.texcoord2 = TRANSFORM_TEX(v.texcoord2, _ShadowTex);
return o;
}
half4 frag(v2f i) : SV_Target
{
const half4 color = tex2D(_MainTex, i.texcoord);
const half4 colorShadow = tex2D(_ShadowTex, i.texcoord2);
half4 mixedColor = color * colorShadow / (1 - _Exposure);
mixedColor.a = _Alpha; // use global alpha
return mixedColor;
}
ENDCG
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 54296b5ef906d4d219289838c47b2f01
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:
+3 -3
View File
@@ -24,7 +24,7 @@ RenderSettings:
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_AmbientMode: 3
m_SubtractiveShadowColor: {r: 1, g: 1, b: 1, a: 1}
m_SkyboxMaterial: {fileID: 0}
m_HaloStrength: 0.5
@@ -97,8 +97,8 @@ LightmapSettings:
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}
m_LightingDataAsset: {fileID: 112000000, guid: b024d577cdecd974eab12c932a37f51b, type: 2}
m_LightingSettings: {fileID: 4890085278179872738, guid: b0ad69fd7711b6842b5f287b194ede35, type: 2}
--- !u!196 &4
NavMeshSettings:
serializedVersion: 2
@@ -32,7 +32,6 @@ namespace Core.DataLoader
DxtHeader header = DxtHeader.ReadHeader(reader);
var format = header.DxtPixelFormat.Format;
hasAlphaChannel = true;
_width = header.Width;
_height = header.Height;
@@ -40,9 +39,11 @@ namespace Core.DataLoader
switch (format)
{
case "DXT1":
hasAlphaChannel = false;
LoadDxt1Texture(data);
break;
case "DXT3":
hasAlphaChannel = true;
LoadDxt3Texture(data);
break;
case "DXT5":
@@ -11,6 +11,7 @@ namespace Core.DataReader.Cpk
using System.Runtime.InteropServices;
using System.Text;
using Lzo;
using UnityEngine;
using Utils;
/// <summary>
@@ -94,6 +95,33 @@ namespace Core.DataReader.Cpk
BuildCrcIndexMap();
}
/// <summary>
/// Extract the complete archive to the specified destination
/// </summary>
public void ExtractTo(string outputFolder)
{
ExtractToInternal(outputFolder, GetRootEntries());
}
private void ExtractToInternal(string outputFolder, IEnumerable<CpkEntry> nodes)
{
foreach (CpkEntry node in nodes)
{
var relativePath = node.VirtualPath.Replace(
CpkConstants.DirectorySeparator, Path.DirectorySeparatorChar);
if (node.IsDirectory)
{
new DirectoryInfo(outputFolder + relativePath).Create();
ExtractToInternal(outputFolder, node.Children);
}
else
{
File.WriteAllBytes(outputFolder + relativePath, ReadAllBytes(node.VirtualPath));
}
}
}
/// <summary>
/// Check if file exists inside the archive.
/// </summary>
@@ -152,7 +152,7 @@ namespace Core.DataReader.Cvd
{
public CvdVertex[][] FrameVertices;
public int[] Triangles;
public byte BlendFlag;
public GameBoxBlendFlag BlendFlag;
public GameBoxMaterial Material;
public string TextureName;
public float[] AnimationTimeKeys;
@@ -173,12 +173,12 @@ namespace Core.DataReader.Cvd
public class CvdAnimationScaleKeyFrame : CvdAnimationKeyFrame
{
public Vector3 Scale { get; set; }
public GameBoxQuaternion Rotation { get; set; }
public Quaternion Rotation { get; set; }
}
public class CvdAnimationRotationKeyFrame : CvdAnimationKeyFrame
{
public GameBoxQuaternion Rotation { get; set; }
public Quaternion Rotation { get; set; }
}
/// <summary>
@@ -193,7 +193,7 @@ namespace Core.DataReader.Cvd
{
KeyType = type,
Time = positionKey.TcbKey.AnimationKey.Time,
Position = positionKey.Value,
Position = GameBoxInterpreter.CvdPositionToUnityPosition(positionKey.Value),
};
break;
}
@@ -204,7 +204,7 @@ namespace Core.DataReader.Cvd
{
KeyType = type,
Time = positionKey.AnimationKey.Time,
Position = positionKey.Value,
Position = GameBoxInterpreter.CvdPositionToUnityPosition(positionKey.Value),
};
break;
}
@@ -215,7 +215,7 @@ namespace Core.DataReader.Cvd
{
KeyType = type,
Time = positionKey.AnimationKey.Time,
Position = positionKey.Value,
Position = GameBoxInterpreter.CvdPositionToUnityPosition(positionKey.Value),
};
break;
}
@@ -248,13 +248,13 @@ namespace Core.DataReader.Cvd
{
KeyType = type,
Time = rotationKey.TcbKey.AnimationKey.Time,
Rotation = new GameBoxQuaternion()
Rotation = GameBoxInterpreter.CvdQuaternionToUnityQuaternion(new GameBoxQuaternion()
{
X = quaternion.x,
Y = quaternion.y,
Z = quaternion.z,
W = quaternion.w,
}
})
};
break;
}
@@ -265,7 +265,7 @@ namespace Core.DataReader.Cvd
{
KeyType = type,
Time = rotationKey.AnimationKey.Time,
Rotation = rotationKey.Value
Rotation = GameBoxInterpreter.CvdQuaternionToUnityQuaternion(rotationKey.Value)
};
break;
}
@@ -276,7 +276,7 @@ namespace Core.DataReader.Cvd
{
KeyType = type,
Time = rotationKey.AnimationKey.Time,
Rotation = rotationKey.Value
Rotation = GameBoxInterpreter.CvdQuaternionToUnityQuaternion(rotationKey.Value)
};
break;
}
@@ -308,8 +308,8 @@ namespace Core.DataReader.Cvd
{
KeyType = type,
Time = scaleKey.TcbKey.AnimationKey.Time,
Scale = scaleKey.Value,
Rotation = scaleKey.Rotation
Scale = GameBoxInterpreter.CvdScaleToUnityScale(scaleKey.Value),
Rotation = GameBoxInterpreter.CvdQuaternionToUnityQuaternion(scaleKey.Rotation)
};
break;
}
@@ -320,8 +320,8 @@ namespace Core.DataReader.Cvd
{
KeyType = type,
Time = scaleKey.AnimationKey.Time,
Scale = scaleKey.Value,
Rotation = scaleKey.Rotation
Scale = GameBoxInterpreter.CvdScaleToUnityScale(scaleKey.Value),
Rotation = GameBoxInterpreter.CvdQuaternionToUnityQuaternion(scaleKey.Rotation)
};
break;
}
@@ -332,8 +332,8 @@ namespace Core.DataReader.Cvd
{
KeyType = type,
Time = scaleKey.AnimationKey.Time,
Scale = scaleKey.Value,
Rotation = scaleKey.Rotation
Scale = GameBoxInterpreter.CvdScaleToUnityScale(scaleKey.Value),
Rotation = GameBoxInterpreter.CvdQuaternionToUnityQuaternion(scaleKey.Rotation)
};
break;
}
@@ -352,9 +352,6 @@ namespace Core.DataReader.Cvd
var numberOfFrames = reader.ReadInt32();
var numberOfVertices = reader.ReadInt32();
//var vertexType = GameBoxVertexType.XYZ | GameBoxVertexType.Normal | GameBoxVertexType.UV0;
//var vertexSize = GameBoxVertex.GetSize((uint)vertexType);
var frameVertices = new CvdVertex[numberOfFrames][];
for (var i = 0; i < numberOfFrames; i++)
{
@@ -362,9 +359,12 @@ namespace Core.DataReader.Cvd
for (var j = 0; j < numberOfVertices; j++)
{
Vector2 uv = reader.ReadVector2();
Vector3 normal = reader.ReadVector3();
Vector3 position = reader.ReadVector3();
Vector3 normal = GameBoxInterpreter.ToUnityNormal(reader.ReadVector3());
Vector3 position = GameBoxInterpreter.CvdPositionToUnityPosition(reader.ReadVector3());
// Quick fix for the missing/wrong normals
if (normal == Vector3.zero) normal = Vector3.up;
vertices[j] = new CvdVertex()
{
Normal = normal,
@@ -407,7 +407,7 @@ namespace Core.DataReader.Cvd
int codepage)
#endif
{
var blendFlag = reader.ReadByte();
var blendFlag = (GameBoxBlendFlag)reader.ReadByte();
var material = new GameBoxMaterial()
{
@@ -458,11 +458,11 @@ namespace Core.DataReader.Cvd
}
var frameVertices = new CvdVertex[allFrameVertices.Length][];
List<int> triangles;
List<int> indexBuffer;
(triangles, indexBuffer) = CalculateTriangles(indices);
(List<int> triangles, List<int> indexBuffer) = CalculateTriangles(indices);
GameBoxInterpreter.ToUnityTriangles(triangles);
for (var i = 0; i < allFrameVertices.Length; i++)
{
var verts = new CvdVertex[indexBuffer.Count];
@@ -493,7 +493,7 @@ namespace Core.DataReader.Cvd
{
var indexBuffer = new List<int>();
var triangles = new List<int>();
var indexMap = new Dictionary<int, int>();
var index = 0;
for (var j = 0; j < allIndices.Length; j++)
{
@@ -506,17 +506,8 @@ namespace Core.DataReader.Cvd
for (var k = 0; k < 3; k++)
{
if (indexMap.ContainsKey(indices[k]))
{
triangles.Add(indexMap[indices[k]]);
}
else
{
var index = indexBuffer.Count;
indexBuffer.Add(indices[k]);
indexMap[indices[k]] = index;
triangles.Add(index);
}
indexBuffer.Add(indices[k]);
triangles.Add(index++);
}
}
+3
View File
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 6277e4ab422e47bdadc0826e97a1dbe3
timeCreated: 1665782936
@@ -0,0 +1,129 @@
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
namespace Core.DataReader.Data
{
//using System.Runtime.InteropServices;
//[StructLayout(LayoutKind.Explicit)]
public struct EffectDefinition
{
//[FieldOffset(0)]
public uint ClassNameCrc;
//[FieldOffset(4)]
//[MarshalAs (UnmanagedType.ByValArray, SizeConst = 30)]
public string TypeName;
//[FieldOffset(36)]
public uint TypeNameCrc;
//[FieldOffset(40)]
//[MarshalAs (UnmanagedType.ByValArray, SizeConst = 128)]
// Union
public string TextureName;
public string ParticleFileName;
public string SfxFileNamePrefix;
public string VideoFileNamePrefix;
//[FieldOffset(168)]
public int FramesPerRow;
//[FieldOffset(172)]
public int FramesPerColumn;
//[FieldOffset(176)]
public int FrameCount;
//[FieldOffset(180)]
public float FramePerSecond;
//[FieldOffset(184)]
public float InitXPosition;
//[FieldOffset(188)]
public float InitYPosition;
//[FieldOffset(192)]
public float InitZPosition;
//[FieldOffset(196)]
// Union
public float InitYRotation;
public float InitAngle;
//[FieldOffset(200)]
public int InitSize;
//[FieldOffset(204)]
public uint InitColor;
//[FieldOffset(208)]
public int MaxQuadCount;
//[FieldOffset(212)]
public bool IsValid;
//[FieldOffset(213)]
public bool IsAdditiveBlend;
//[FieldOffset(214)]
public bool IsBillboard;
//[FieldOffset(215)]
public bool IsZTestIgnored;
//[FieldOffset(216)]
public float InitXRotation;
//[FieldOffset(220)]
public float InitZRotation;
//[FieldOffset(224)]
public float RotationAngle;
//[FieldOffset(228)]
public float Width;
//[FieldOffset(232)]
public float DivisionCount;
//[FieldOffset(236)]
public float TopShrink;
//[FieldOffset(240)]
public float BottomShrink;
//[FieldOffset(244)]
public float TopRadius;
//[FieldOffset(248)]
public float BottomRadius;
//[FieldOffset(252)]
public float TopRadiusIncreaseSpeed;
//[FieldOffset(256)]
public float BottomRadiusIncreaseSpeed;
//[FieldOffset(260)]
public float TopRiseSpeed;
//[FieldOffset(264)]
public float BottomRiseSpeed;
//[FieldOffset(268)]
public float TextureRepeat;
//[FieldOffset(272)]
//[MarshalAs (UnmanagedType.ByValArray, SizeConst = 2)]
public float[] Param;
}
public class EffectDefinitionFile
{
public EffectDefinition[] EffectDefinitions;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 3c47b38acef943118e9374c4113e7b5e
timeCreated: 1665782973
@@ -0,0 +1,107 @@
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
//#define USE_UNSAFE_BINARY_READER
namespace Core.DataReader.Data
{
using System.IO;
using Extensions;
using Utils;
public static class EffectDefinitionFileReader
{
private const int NUM_OF_EFFECTS = 1324;
public static void Read(byte[] data, int codepage)
{
#if USE_UNSAFE_BINARY_READER
using var reader = new UnsafeBinaryReader(data);
#else
using var stream = new MemoryStream(data);
using var reader = new BinaryReader(stream);
#endif
var effectDefinitions = new EffectDefinition[NUM_OF_EFFECTS];
for (var i = 0; i < NUM_OF_EFFECTS; i++)
{
effectDefinitions[i] = ReadEffectDefinition(reader, codepage);
}
}
#if USE_UNSAFE_BINARY_READER
private static EffectDefinition ReadEffectDefinition(UnsafeBinaryReader reader, int codepage)
#else
private static EffectDefinition ReadEffectDefinition(BinaryReader reader, int codepage)
#endif
{
var effectDefinition = new EffectDefinition();
effectDefinition.ClassNameCrc = reader.ReadUInt32();
effectDefinition.TypeName = reader.ReadString(32, 936);
effectDefinition.TypeNameCrc = reader.ReadUInt32();
// union
{
var unionStr = reader.ReadString(128, 936);
effectDefinition.TextureName = unionStr;
effectDefinition.ParticleFileName = unionStr;
effectDefinition.SfxFileNamePrefix = unionStr;
effectDefinition.VideoFileNamePrefix = unionStr;
}
effectDefinition.FramesPerRow = reader.ReadInt32();
effectDefinition.FramesPerColumn = reader.ReadInt32();
effectDefinition.FrameCount = reader.ReadInt32();
effectDefinition.FramePerSecond = reader.ReadSingle();
effectDefinition.InitXPosition = reader.ReadSingle();
effectDefinition.InitYPosition = reader.ReadSingle();
effectDefinition.InitZPosition = reader.ReadSingle();
// union
{
var unionFloat = reader.ReadSingle();
effectDefinition.InitYRotation = unionFloat;
effectDefinition.InitAngle = unionFloat;
}
effectDefinition.InitSize = reader.ReadInt32();
effectDefinition.InitColor = reader.ReadUInt32();
effectDefinition.MaxQuadCount = reader.ReadInt32();
effectDefinition.IsValid = reader.ReadBoolean();
effectDefinition.IsAdditiveBlend = reader.ReadBoolean();
effectDefinition.IsBillboard = reader.ReadBoolean();
effectDefinition.IsZTestIgnored = reader.ReadBoolean();
effectDefinition.InitXRotation = reader.ReadSingle();
effectDefinition.InitZRotation = reader.ReadSingle();
effectDefinition.RotationAngle = reader.ReadSingle();
effectDefinition.Width = reader.ReadSingle();
effectDefinition.DivisionCount = reader.ReadSingle();
effectDefinition.TopShrink = reader.ReadSingle();
effectDefinition.BottomShrink = reader.ReadSingle();
effectDefinition.TopRadius = reader.ReadSingle();
effectDefinition.BottomRadius = reader.ReadSingle();
effectDefinition.TopRadiusIncreaseSpeed = reader.ReadSingle();
effectDefinition.BottomRadiusIncreaseSpeed = reader.ReadSingle();
effectDefinition.TopRiseSpeed = reader.ReadSingle();
effectDefinition.BottomRiseSpeed = reader.ReadSingle();
effectDefinition.TextureRepeat = reader.ReadSingle();
effectDefinition.Param = new[]
{
reader.ReadSingle(),
reader.ReadSingle(),
};
return effectDefinition;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a324f42c7b6346dc8c98a2c6c377c9d6
timeCreated: 1665784313
+3
View File
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7033622484af4557882d201a3784de14
timeCreated: 1665907414
@@ -0,0 +1,44 @@
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
namespace Core.DataReader.Lgt
{
using GameBox;
using UnityEngine;
[System.Serializable]
public struct LightNode
{
public Matrix4x4 WorldMatrix;
public GameBoxLightType LightType;
public Color LightColor;
public Color AmbientColor;
public bool UseDiffuse;
public bool UseSpecular;
public float NearStart;
public float NearEnd;
public float FarStart;
public float FarEnd;
public GameBoxLightDecayType LightDecayType;
public float DecayRadius;
public GameBoxLightShapeType LightShapeType;
public float Size;
public float Falloff;
public float AspectRatio;
}
public class LgtFile
{
public LightNode[] LightNodes { get; }
public LgtFile(LightNode[] lightNodes)
{
LightNodes = lightNodes;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 25179e1de24d41698cd68a919c3d0990
timeCreated: 1665907430
@@ -0,0 +1,83 @@
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
#define USE_UNSAFE_BINARY_READER
namespace Core.DataReader.Lgt
{
using System;
using System.Collections.Generic;
using System.IO;
using Extensions;
using GameBox;
using Utils;
public static class LgtFileReader
{
public static LgtFile Read(byte[] data)
{
#if USE_UNSAFE_BINARY_READER
using var reader = new UnsafeBinaryReader(data);
#else
using var stream = new MemoryStream(data);
using var reader = new BinaryReader(stream);
#endif
var numOfLightNodes = reader.ReadInt32();
var lightNodes = new List<LightNode>();
for (var i = 0; i < numOfLightNodes; i++)
{
var lightNode = ReadLightNode(reader);
if (Enum.IsDefined(typeof(GameBoxLightType), lightNode.LightType) &&
Enum.IsDefined(typeof(GameBoxLightShapeType), lightNode.LightShapeType))
{
lightNodes.Add(lightNode);
}
}
return new LgtFile(lightNodes.ToArray());
}
#if USE_UNSAFE_BINARY_READER
private static LightNode ReadLightNode(UnsafeBinaryReader reader)
#else
private static LightNode ReadLightNode(BinaryReader reader)
#endif
{
var transformMatrix = new GameBoxMatrix4X4()
{
Xx = reader.ReadSingle(), Xy = reader.ReadSingle(), Xz = reader.ReadSingle(), Xw = reader.ReadSingle(),
Yx = reader.ReadSingle(), Yy = reader.ReadSingle(), Yz = reader.ReadSingle(), Yw = reader.ReadSingle(),
Zx = reader.ReadSingle(), Zy = reader.ReadSingle(), Zz = reader.ReadSingle(), Zw = reader.ReadSingle(),
Tx = reader.ReadSingle(), Ty = reader.ReadSingle(), Tz = reader.ReadSingle(), Tw = reader.ReadSingle()
};
transformMatrix.Tw = 1f;
var lightNode = new LightNode
{
WorldMatrix = GameBoxInterpreter.ToUnityMatrix4x4(transformMatrix),
LightType = (GameBoxLightType)reader.ReadInt32(),
LightColor = Utility.ToColor(reader.ReadSingleArray(4)),
AmbientColor = Utility.ToColor(reader.ReadSingleArray(4)),
UseDiffuse = reader.ReadBoolean(),
UseSpecular = reader.ReadBoolean(),
NearStart = reader.ReadSingle(),
NearEnd = reader.ReadSingle(),
FarStart = reader.ReadSingle(),
FarEnd = reader.ReadSingle(),
LightDecayType = (GameBoxLightDecayType)reader.ReadInt32(),
DecayRadius = reader.ReadSingle(),
LightShapeType = (GameBoxLightShapeType)reader.ReadInt32(),
Size = reader.ReadSingle(),
Falloff = reader.ReadSingle(),
AspectRatio = reader.ReadSingle()
};
return lightNode;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f29568c4d19d4fcca931e8bf250ccc01
timeCreated: 1665907439
@@ -81,13 +81,13 @@ namespace Core.DataReader.Mv3
public Mv3Attribute[] Attributes;
public Mv3VertFrame[] Frames;
public Vector2[] TexCoords;
public Vector3[] Normals;
}
public struct VertexAnimationKeyFrame
{
public uint Tick;
public Vector3[] Vertices;
public Vector3[] Normals;
public int[] Triangles;
public Vector2[] Uv;
}
@@ -74,8 +74,9 @@ namespace Core.DataReader.Mv3
for (var i = 0; i < numberOfMeshes; i++)
{
Mv3Mesh mesh = ReadMesh(reader, codepage);
meshes[i] = mesh;
meshKeyFrames[i] = CalculateKeyFrameVertices(mesh);
mesh.Normals = Utility.CalculateNormals(meshKeyFrames[i][0].Vertices, meshKeyFrames[i][0].Triangles);
meshes[i] = mesh;
}
return new Mv3File(version,
@@ -185,38 +186,28 @@ namespace Core.DataReader.Mv3
{
var triangles = new List<int>();
var texCoords = mv3Mesh.TexCoords;
var indexMap = new Dictionary<int, int>();
var keyFrameInfo = new List<(Vector3 vertex, Vector2 uv)>[mv3Mesh.Frames.Length]
.Select(item=>new List<(Vector3 vertex, Vector2 uv)>()).ToArray();
var triangleIndex = 0;
for (var i = 0; i < mv3Mesh.Attributes[0].IndexBuffers.Length; i++)
{
Mv3IndexBuffer indexBuffer = mv3Mesh.Attributes[0].IndexBuffers[i];
for (var j = 0; j < 3; j++)
{
var hash = indexBuffer.TriangleIndex[j] * texCoords.Length + indexBuffer.TexCoordIndex[j];
if (indexMap.ContainsKey(hash))
for (var k = 0; k < mv3Mesh.Frames.Length; k++)
{
triangles.Add(indexMap[hash]);
Mv3VertFrame frame = mv3Mesh.Frames[k];
Mv3Vert vertex = frame.Vertices[indexBuffer.TriangleIndex[j]];
keyFrameInfo[k].Add((GameBoxInterpreter
.ToUnityVertex(new Vector3(vertex.X, vertex.Y, vertex.Z),
GameBoxInterpreter.GameBoxMv3UnitToUnityUnit),
texCoords[indexBuffer.TexCoordIndex[j]]));
}
else
{
var index = indexMap.Keys.Count;
for (var k = 0; k < mv3Mesh.Frames.Length; k++)
{
Mv3VertFrame frame = mv3Mesh.Frames[k];
Mv3Vert vertex = frame.Vertices[indexBuffer.TriangleIndex[j]];
keyFrameInfo[k].Add((GameBoxInterpreter
.ToUnityVertex(new Vector3(vertex.X, vertex.Y, vertex.Z),
GameBoxInterpreter.GameBoxMv3UnitToUnityUnit),
texCoords[indexBuffer.TexCoordIndex[j]]));
}
indexMap[hash] = index;
triangles.Add(index);
}
triangles.Add(triangleIndex++);
}
}
@@ -7,9 +7,11 @@ namespace Core.DataReader.Nav
{
using System;
using System.IO;
using System.Linq;
using Extensions;
using GameBox;
using UnityEngine;
using Utils;
public static class NavFileReader
{
@@ -106,7 +108,7 @@ namespace Core.DataReader.Nav
var vertices = new Vector3[numberOfVertices];
for (var i = 0; i < numberOfVertices; i++)
{
vertices[i] = reader.ReadVector3();
vertices[i] = GameBoxInterpreter.ToUnityPosition(reader.ReadVector3());
}
var triangles = new int[numberOfFaces * 3];
@@ -118,6 +120,25 @@ namespace Core.DataReader.Nav
triangles[index + 2] = reader.ReadUInt16();
}
// Some of the nav meshes in the original game are upside down (don't know why),
// so we need to flip them if that's the case. You might argue that we can just
// make the mesh double sided, but that would cause some other issues (trust me).
{
Vector3[] normals = Utility.CalculateNormals(vertices, triangles);
for (var i = 0; i < numberOfFaces; i++)
{
var index = i * 3;
if (normals[triangles[index]].y +
normals[triangles[index + 1]].y +
normals[triangles[index + 2]].y < 0)
{
// Change the winding order of the face.
(triangles[index], triangles[index + 1]) = (triangles[index + 1], triangles[index]);
}
}
}
return new NavFaceLayer()
{
Vertices = vertices,
@@ -28,7 +28,6 @@ namespace Core.DataReader.Pol
{
public Vector3[] Positions;
public Vector3[] Normals;
public float[] Radii;
public Color32[] DiffuseColors;
public Color32[] SpecularColors;
public Vector2[][] Uvs;
@@ -44,7 +43,7 @@ namespace Core.DataReader.Pol
public struct PolTexture
{
public uint BlendFlag; // 0--opaque, 1--alpha blend, 2--invert color blend, 3--add
public GameBoxBlendFlag BlendFlag; // 0--opaque, 1--alpha blend, 2--invert color blend, 3--add
public GameBoxMaterial Material;
public string[] TextureNames;
public int VertStart;
@@ -137,7 +137,6 @@ namespace Core.DataReader.Pol
var positions = new Vector3[numberOfVertices];
var normals = new Vector3[numberOfVertices];
var diffuseColors = new Color32[numberOfVertices];
var radii = new float[numberOfVertices];
var specularColors = new Color32[numberOfVertices];
var uvs = new Vector2[4][];
@@ -163,9 +162,7 @@ namespace Core.DataReader.Pol
}
if ((vertexTypeFlag & GameBoxVertexType.Normal) != 0)
{
normals[i] = GameBoxInterpreter
.ToUnityVertex(reader.ReadVector3(),
GameBoxInterpreter.GameBoxUnitToUnityUnit);
normals[i] = GameBoxInterpreter.ToUnityNormal(reader.ReadVector3());
}
if ((vertexTypeFlag & GameBoxVertexType.Diffuse) != 0)
{
@@ -199,6 +196,9 @@ namespace Core.DataReader.Pol
var y = reader.ReadSingle();
uvs[3][i] = new Vector2(x, y);
}
// Quick fix for the missing/wrong normals
if (normals[i] == Vector3.zero) normals[i] = Vector3.up;
}
var vertexInfo = new PolVertexInfo()
@@ -206,7 +206,6 @@ namespace Core.DataReader.Pol
Positions = positions,
Normals = normals,
DiffuseColors = diffuseColors,
Radii = radii,
SpecularColors = specularColors,
Uvs = uvs,
};
@@ -235,7 +234,7 @@ namespace Core.DataReader.Pol
private static PolTexture ReadTextureInfo(BinaryReader reader, int version, int codepage)
#endif
{
var blendFlag = reader.ReadUInt32();
var blendFlag = (GameBoxBlendFlag)reader.ReadUInt32();
var material = new GameBoxMaterial()
{
@@ -270,13 +269,13 @@ namespace Core.DataReader.Pol
for (var i = 0; i < numberOfFaces; i++)
{
var index = i * 3;
var x = reader.ReadInt16();
var y = reader.ReadInt16();
var z = reader.ReadInt16();
(triangles[index], triangles[index + 1], triangles[index + 2]) =
GameBoxInterpreter.ToUnityTriangle((x, y, z));
triangles[index] = reader.ReadInt16();
triangles[index + 1] = reader.ReadInt16();
triangles[index + 2] = reader.ReadInt16();
}
GameBoxInterpreter.ToUnityTriangles(triangles);
return new PolTexture()
{
BlendFlag = blendFlag,
@@ -168,6 +168,11 @@ namespace Core.DataReader.Scn
string.Equals(modelAName, modelBName, StringComparison.OrdinalIgnoreCase);
#endif
}
public override string ToString()
{
return $"{CityName.ToLower()}_{Name.ToLower()}_{LightMap}";
}
}
[System.Serializable]
@@ -204,6 +204,25 @@ namespace Core.FileSystem
}
}
/// <summary>
/// Extract all archives to the specified destination
/// </summary>
public void ExtractTo(string outputFolder)
{
foreach ((string cpkFileName, CpkArchive cpkArchive) in _cpkArchives)
{
var outputDir = outputFolder + cpkFileName + Path.DirectorySeparatorChar;
if (!Directory.Exists(outputDir))
{
Directory.CreateDirectory(outputDir);
}
cpkArchive.ExtractTo(outputDir);
Debug.Log($"{cpkFileName} extracted to {outputDir}");
}
}
/// <summary>
/// Search files using keyword.
/// </summary>
@@ -64,6 +64,11 @@ namespace Core.FileSystem
/// </summary>
public void DisposeAllInMemoryArchives();
/// <summary>
/// Extract all archives to the specified destination
/// </summary>
public void ExtractTo(string outputFolder);
/// <summary>
/// Search files using keyword.
/// </summary>
@@ -55,6 +55,14 @@ namespace Core.GameBox
scale.y);
}
public static Vector3 ToUnityNormal(Vector3 normal)
{
return new Vector3(
-normal.x,
normal.y,
normal.z);
}
public static Quaternion CvdQuaternionToUnityQuaternion(GameBoxQuaternion quaternion)
{
return new Quaternion(-quaternion.X, quaternion.Z, -quaternion.Y, quaternion.W);
@@ -64,6 +72,15 @@ namespace Core.GameBox
{
return new Quaternion(-quaternion.X, quaternion.Y, quaternion.Z, quaternion.W);
}
public static Quaternion LgtQuaternionToUnityQuaternion(GameBoxQuaternion quaternion)
{
var rotation = new Quaternion(quaternion.X, quaternion.Y, -quaternion.Z, quaternion.W);
rotation.eulerAngles = new Vector3(rotation.eulerAngles.x + 90f,
-rotation.eulerAngles.y,
rotation.eulerAngles.z);
return rotation;
}
public static Quaternion ToUnityRotation(float pitch, float yaw, float roll)
{
@@ -77,33 +94,15 @@ namespace Core.GameBox
vector3.y / scale,
vector3.z / scale);
}
// Since GameBox's rendering pipeline uses different internal axis system
// Here we are switching x and y index to minor it back to the Unity axis
// for triangles
public static (short x, short y, short z) ToUnityTriangle((short x, short y, short z) triangle)
{
return (triangle.y, triangle.x, triangle.z);
}
public static void ToUnityTriangles(List<int> triangles)
{
for (var i = 0; i < triangles.Count; i += 3)
{
(triangles[i], triangles[i + 1]) = (triangles[i + 1], triangles[i]);
}
triangles.Reverse();
}
public static int[] ToUnityTriangles(ReadOnlySpan<int> triangles)
public static void ToUnityTriangles(int[] triangles)
{
var indices = new int[triangles.Length];
for (var i = 0; i < triangles.Length; i += 3)
{
indices[i] = triangles[i + 1];
indices[i + 1] = triangles[i];
indices[i + 2] = triangles[i + 2];
}
return indices;
Array.Reverse(triangles);
}
public static bool IsPositionInsideRect(GameBoxRect rect, Vector2Int position)
@@ -72,6 +72,34 @@ namespace Core.GameBox
public const int FlagMask = (1 << 31);
}
public enum GameBoxBlendFlag
{
Opaque, // opaque
AlphaBlend, // src.alpha, 1-src.alpha, +
InvertColorBlend, // srcAlpha, One , +
AdditiveBlend, //
}
public enum GameBoxLightType
{
Omni, // point light
Spot, // spot light
Directional, // directional light
}
public enum GameBoxLightDecayType
{
None,
Distance,
Square,
}
public enum GameBoxLightShapeType
{
Cone,
Square,
}
public static class GameBoxVertex
{
public static int GetSize(uint vertexType)
@@ -29,9 +29,15 @@ namespace Core.Renderer
public IEnumerator PlaySpriteAnimation(Sprite[] sprites,
float fps,
int loopCount)
int loopCount,
Material material = default)
{
_isPlaying = true;
if (material != default)
{
_spriteRenderer.material = material;
}
if (loopCount == -1)
{
+13 -6
View File
@@ -12,6 +12,13 @@ namespace Core.Renderer
{
private Skybox _skybox;
private static readonly int RightTexturePropertyID = Shader.PropertyToID("_RightTex");
private static readonly int BackTexturePropertyID = Shader.PropertyToID("_BackTex");
private static readonly int LeftTexturePropertyID = Shader.PropertyToID("_LeftTex");
private static readonly int FrontTexturePropertyID = Shader.PropertyToID("_FrontTex");
private static readonly int UpTexturePropertyID = Shader.PropertyToID("_UpTex");
private static readonly int DownTexturePropertyID = Shader.PropertyToID("_DownTex");
public void Render(Texture2D[] textures)
{
var mainCamera = GetComponent<Camera>();
@@ -32,12 +39,12 @@ namespace Core.Renderer
private static Material CreateSkyboxMaterial(Texture2D[] textures)
{
var material = new Material(Shader.Find("Skybox/6 Sided"));
material.SetTexture("_RightTex", textures[0]);
material.SetTexture("_BackTex", textures[1]);
material.SetTexture("_LeftTex", textures[2]);
material.SetTexture("_FrontTex", textures[3]);
material.SetTexture("_UpTex", textures[4]);
material.SetTexture("_DownTex", textures[5]);
material.SetTexture(RightTexturePropertyID, textures[0]);
material.SetTexture(BackTexturePropertyID, textures[1]);
material.SetTexture(LeftTexturePropertyID, textures[2]);
material.SetTexture(FrontTexturePropertyID, textures[3]);
material.SetTexture(UpTexturePropertyID, textures[4]);
material.SetTexture(DownTexturePropertyID, textures[5]);
return material;
}
}
@@ -5,10 +5,10 @@
namespace Core.Renderer
{
using System;
using UnityEngine;
using UnityEngine.Rendering;
public sealed class StaticMeshRenderer : MonoBehaviour
public sealed class StaticMeshRenderer : MonoBehaviour, IDisposable
{
private MeshRenderer _meshRenderer;
private MeshFilter _meshFilter;
@@ -16,58 +16,15 @@ namespace Core.Renderer
public Mesh Render(ref Vector3[] vertices,
ref int[] triangles,
ref Vector3[] normals,
ref Vector2[] uv,
ref Material material,
ref Vector2[] mainTextureUvs,
ref Vector2[] secondaryTextureUvs,
ref Material[] materials,
bool isDynamic)
{
Dispose();
_meshRenderer = gameObject.AddComponent<MeshRenderer>();
//_meshRenderer.receiveShadows = false;
//_meshRenderer.lightProbeUsage = LightProbeUsage.Off;
_meshRenderer.sharedMaterial = material;
_meshFilter = gameObject.AddComponent<MeshFilter>();
var mesh = new Mesh();
if (isDynamic)
{
mesh.MarkDynamic();
}
mesh.SetVertices(vertices);
mesh.SetTriangles(triangles, 0);
mesh.SetNormals(normals);
mesh.SetUVs(0, uv);
if (triangles.Length == 0)
{
// https://docs.unity3d.com/ScriptReference/Mesh.RecalculateBounds.html
// After modifying vertices you should call this function to ensure the
// bounding volume is correct. Assigning triangles automatically
// recalculates the bounding volume.
mesh.RecalculateBounds();
}
_meshFilter.sharedMesh = mesh;
return mesh;
}
public Mesh Render(ref Vector3[] vertices,
ref int[] triangles,
ref Vector3[] normals,
ref Vector2[] mainTextureUv,
ref Vector2[] secondaryTextureUv,
ref Material material,
bool isDynamic)
{
Dispose();
_meshRenderer = gameObject.AddComponent<MeshRenderer>();
//_meshRenderer.receiveShadows = false;
//_meshRenderer.lightProbeUsage = LightProbeUsage.Off;
_meshRenderer.sharedMaterial = material;
_meshRenderer.sharedMaterials = materials;
_meshFilter = gameObject.AddComponent<MeshFilter>();
var mesh = new Mesh();
@@ -79,8 +36,8 @@ namespace Core.Renderer
mesh.SetVertices(vertices);
mesh.SetTriangles(triangles, 0);
mesh.SetNormals(normals);
mesh.SetUVs(0, mainTextureUv);
mesh.SetUVs(1, secondaryTextureUv);
mesh.SetUVs(0, mainTextureUvs);
mesh.SetUVs(1, secondaryTextureUvs);
if (triangles.Length == 0)
{
@@ -121,7 +78,7 @@ namespace Core.Renderer
Dispose();
}
private void Dispose()
public void Dispose()
{
if (_meshFilter != null)
{
@@ -131,7 +88,11 @@ namespace Core.Renderer
if (_meshRenderer != null)
{
Destroy(_meshRenderer.sharedMaterial);
foreach (Material material in _meshRenderer.sharedMaterials)
{
Destroy(material);
}
Destroy(_meshRenderer);
}
}
@@ -156,11 +156,6 @@ namespace Core.Utils
return Encoding.GetEncoding(codepage).GetString(strBytes, 0, i);
}
public void Close()
{
Dispose(true);
}
private bool _disposedValue;
private void Dispose(bool disposing)
{
+38
View File
@@ -164,6 +164,44 @@ namespace Core.Utils
return finalBounds;
}
public static Vector3[] CalculateNormals(Vector3[] vertices, int[] triangles)
{
Vector3[] normals = new Vector3[vertices.Length];
for (var face = 0; face < triangles.Length / 3; face++)
{
int v1 = triangles[face * 3];
int v2 = triangles[face * 3 + 1];
int v3 = triangles[face * 3 + 2];
Vector3 pt1 = vertices[v1];
Vector3 pt2 = vertices[v2];
Vector3 pt3 = vertices[v3];
Vector3 d1 = pt2 - pt1;
Vector3 d2 = pt3 - pt1;
Vector3 normal = Vector3.Normalize(Vector3.Cross(d1, d2));
normals[v1] += normal;
normals[v2] += normal;
normals[v3] += normal;
}
for (var i = 0; i < normals.Length; i++)
{
if (normals[i] == Vector3.zero)
{
normals[i] = Vector3.up;
}
else
{
normals[i] = Vector3.Normalize(normals[i]);
}
}
return normals;
}
public static void DrawBounds(Bounds b, float duration = 1000)
{
var p1 = new Vector3(b.min.x, b.min.y, b.min.z);
+2 -2
View File
@@ -39,7 +39,7 @@ namespace Editor
BuildTargetGroup.iOS,
};
}
private static NamedBuildTarget[] GetAllSupportedNamedBuildTargets()
{
return new[]
@@ -49,7 +49,7 @@ namespace Editor
NamedBuildTarget.iOS,
};
}
private static void ApplyPlayerSettingsForVariant(string appName)
{
PlayerSettings.productName = appName;
@@ -166,12 +166,20 @@ namespace Pal3.Actor
$"{FileConstants.WeaponFolderName}{separator}{weaponName}{separator}{weaponName}.pol";
(PolFile polFile, ITextureResourceProvider weaponTextureProvider) = _resourceProvider.GetPol(weaponPath);
_mv3AnimationRenderer.Init(mv3File, textureProvider, _tintColor,
polFile, weaponTextureProvider, Color.white);
_mv3AnimationRenderer.Init(mv3File,
_resourceProvider.GetMaterialFactory(),
textureProvider,
_tintColor,
polFile,
weaponTextureProvider,
Color.white);
}
else
{
_mv3AnimationRenderer.Init(mv3File, textureProvider, _tintColor);
_mv3AnimationRenderer.Init(mv3File,
_resourceProvider.GetMaterialFactory(),
textureProvider,
_tintColor);
}
_mv3AnimationRenderer.AnimationLoopPointReached += AnimationLoopPointReached;
@@ -183,7 +191,10 @@ namespace Pal3.Actor
ActorActionType action = ActorConstants.ActionNames
.FirstOrDefault(a => a.Value.Equals(_currentAction)).Key;
#if !RTX_ON
SetupShadow(action);
#endif
SetupCollider();
SetupRigidBody();
}
@@ -51,6 +51,7 @@ namespace Pal3.Actor
private readonly Path _currentPath = new ();
private WaitUntilCanceled _movementWaiter;
private CancellationTokenSource _movementCts = new ();
private bool _isDuringCollision;
private Vector3 _lastKnownValidPositionWhenCollisionEnter;
@@ -106,6 +107,7 @@ namespace Pal3.Actor
{
_currentPath.Clear();
_movementWaiter?.CancelWait();
_movementCts?.Cancel();
CommandExecutorRegistry<ICommand>.Instance.UnRegister(this);
}
@@ -418,7 +420,9 @@ namespace Pal3.Actor
_actionController.PerformAction(_actor.GetIdleAction());
var waypoints = _currentPath.GetAllWayPoints();
waypoints.Reverse();
StartCoroutine(WaitForSomeTimeAndFollowPath(waypoints.ToArray(), _currentPath.MovementMode));
StartCoroutine(WaitForSomeTimeAndFollowPath(waypoints.ToArray(),
_currentPath.MovementMode,
_movementCts.Token));
break;
}
}
@@ -433,10 +437,13 @@ namespace Pal3.Actor
_currentPath.Clear();
}
private IEnumerator WaitForSomeTimeAndFollowPath(Vector3[] waypoints, int mode)
private IEnumerator WaitForSomeTimeAndFollowPath(Vector3[] waypoints, int mode, CancellationToken cancellationToken)
{
yield return new WaitForSeconds(Random.Range(3, 8));
SetupPath(waypoints, mode, EndOfPathActionType.Reverse, ignoreObstacle: true);
if (!cancellationToken.IsCancellationRequested)
{
SetupPath(waypoints, mode, EndOfPathActionType.Reverse, ignoreObstacle: true);
}
}
public IEnumerator MoveDirectlyTo(Vector3 position, int mode)
@@ -455,8 +462,9 @@ namespace Pal3.Actor
private IEnumerator FindPathAndMoveToTilePosition(Vector2Int position,
int mode,
EndOfPathActionType endOfPathAction,
CancellationToken cancellationToken,
bool moveTowardsPositionIfNoPathFound = false,
string specialAction = null)
string specialAction = default)
{
Vector2Int[] path = Array.Empty<Vector2Int>();
Vector2Int fromTile = _tilemap.GetTilePosition(transform.position, _currentLayerIndex);
@@ -478,6 +486,8 @@ namespace Pal3.Actor
yield return null;
}
if (cancellationToken.IsCancellationRequested) yield break;
if (path.Length <= 0)
{
if (moveTowardsPositionIfNoPathFound)
@@ -550,7 +560,7 @@ namespace Pal3.Actor
_movementWaiter = new WaitUntilCanceled(this);
CommandDispatcher<ICommand>.Instance.Dispatch(new ScriptRunnerWaitRequest(_movementWaiter));
StartCoroutine(FindPathAndMoveToTilePosition(new Vector2Int(command.TileX, command.TileZ),
command.Mode, EndOfPathActionType.Idle));
command.Mode, EndOfPathActionType.Idle, _movementCts.Token));
}
#if PAL3A
@@ -561,7 +571,7 @@ namespace Pal3.Actor
_movementWaiter = new WaitUntilCanceled(this);
CommandDispatcher<ICommand>.Instance.Dispatch(new ScriptRunnerWaitRequest(_movementWaiter));
StartCoroutine(FindPathAndMoveToTilePosition(new Vector2Int(command.TileX, command.TileZ),
mode: 0, EndOfPathActionType.Idle, specialAction: command.Action));
mode: 0, EndOfPathActionType.Idle, _movementCts.Token, specialAction: command.Action));
}
#endif
@@ -591,6 +601,7 @@ namespace Pal3.Actor
new Vector2Int(command.TileX, command.TileZ),
command.Mode,
EndOfPathActionType.DisposeSelf,
_movementCts.Token,
true));
}
@@ -598,6 +609,8 @@ namespace Pal3.Actor
{
if (_actor.Info.Id != command.ActorId) return;
_movementWaiter?.CancelWait();
_movementCts?.Cancel();
_movementCts = new CancellationTokenSource();
_currentPath.Clear();
}
@@ -610,7 +623,13 @@ namespace Pal3.Actor
public void Execute(ActorActivateCommand command)
{
if (_actor.Info.Id != command.ActorId) return;
if (command.IsActive == 0) _currentPath.Clear();
if (command.IsActive == 0)
{
_movementWaiter?.CancelWait();
_movementCts?.Cancel();
_movementCts = new CancellationTokenSource();
_currentPath.Clear();
}
}
}
}
+8 -6
View File
@@ -387,27 +387,27 @@ namespace Pal3.Camera
_freeToRotate = false;
_lookAtPointYOffset = SCENE_STORY_B_ROOM_HEIGHT /
GameBoxInterpreter.GameBoxUnitToUnityUnit;
_camera.nearClipPlane = 0.5f;
_camera.nearClipPlane = 1f;
_camera.farClipPlane = 500f;
ApplyDefaultSettings(1);
break;
case ScnSceneType.StoryA:
_freeToRotate = true;
_lookAtPointYOffset = 0;
_camera.nearClipPlane = 1f;
_camera.nearClipPlane = 2f;
_camera.farClipPlane = 800f;
ApplyDefaultSettings(0);
break;
case ScnSceneType.Maze:
_freeToRotate = true;
_lookAtPointYOffset = 0;
_camera.nearClipPlane = 1f;
_camera.nearClipPlane = 2f;
_camera.farClipPlane = 800f;
ApplyDefaultSettings(0);
break;
default:
_lookAtPointYOffset = 0;
_camera.nearClipPlane = 0.5f;
_camera.nearClipPlane = 1f;
_camera.farClipPlane = 500f;
ApplyDefaultSettings(0);
break;
@@ -709,7 +709,8 @@ namespace Pal3.Camera
{
if (_sceneManager.GetCurrentScene() is not { } currentScene) return;
if (currentScene.GetSceneInfo().SceneType != ScnSceneType.StoryB)
if (_gameStateManager.GetCurrentState() == GameState.Gameplay &&
currentScene.GetSceneInfo().SceneType != ScnSceneType.StoryB)
{
var cameraTransform = _camera.transform;
_cameraLastKnownSceneState.Add((
@@ -731,7 +732,8 @@ namespace Pal3.Camera
ApplySceneSettings(notification.NewSceneInfo);
// Apply the last known scene state if found in record.
if (notification.NewSceneInfo.SceneType != ScnSceneType.StoryB)
if (_gameStateManager.GetCurrentState() == GameState.Gameplay &&
notification.NewSceneInfo.SceneType != ScnSceneType.StoryB)
{
if (_cameraLastKnownSceneState.Count > 0 && _cameraLastKnownSceneState.Any(_ =>
_.sceneInfo.ModelEquals(notification.NewSceneInfo)))
@@ -18,6 +18,7 @@ namespace Pal3.Data
using Core.DataReader.Cpk;
using Core.DataReader.Cvd;
using Core.DataReader.Ini;
using Core.DataReader.Lgt;
using Core.DataReader.Mv3;
using Core.DataReader.Nav;
using Core.DataReader.Pol;
@@ -26,8 +27,10 @@ namespace Pal3.Data
using Core.FileSystem;
using Core.Utils;
using MetaData;
using Renderer;
using UnityEngine;
using Debug = UnityEngine.Debug;
using Object = UnityEngine.Object;
/// <summary>
/// Single resource provider for accessing game data.
@@ -41,15 +44,19 @@ namespace Pal3.Data
private readonly ICpkFileSystem _fileSystem;
private readonly ITextureLoaderFactory _textureLoaderFactory;
private readonly IMaterialFactory _materialFactory;
private readonly int _codepage;
private TextureCache _textureCache;
private readonly Dictionary<string, Sprite> _spriteCache = new ();
private readonly Dictionary<string, (PolFile PolFile, ITextureResourceProvider TextureProvider)> _polCache = new ();
private readonly Dictionary<string, (CvdFile PolFile, ITextureResourceProvider TextureProvider)> _cvdCache = new ();
private readonly Dictionary<string, (Mv3File mv3File, ITextureResourceProvider textureProvider)> _mv3Cache = new ();
private readonly Dictionary<string, ActorConfigFile> _actorConfigCache = new (); // Cache forever
private readonly Dictionary<string, AudioClip> _audioClipCache = new ();
private readonly Dictionary<int, Object> _vfxEffectPrefabCache = new ();
// Cache player actor movement sfx audio clips
private readonly HashSet<string> _audioClipCacheList = new ()
{
@@ -73,17 +80,19 @@ namespace Pal3.Data
public GameResourceProvider(ICpkFileSystem fileSystem,
ITextureLoaderFactory textureLoaderFactory,
IMaterialFactory materialFactory,
int codepage)
{
_fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem));
_textureLoaderFactory = textureLoaderFactory ?? throw new ArgumentNullException(nameof(textureLoaderFactory));
_materialFactory = materialFactory ?? throw new ArgumentNullException(nameof(materialFactory));
_codepage = codepage;
CommandExecutorRegistry<ICommand>.Instance.Register(this);
}
public void Dispose()
{
_textureCache.DisposeAll();
_textureCache?.DisposeAll();
_spriteCache.Clear();
_polCache.Clear();
_mv3Cache.Clear();
@@ -107,6 +116,11 @@ namespace Pal3.Data
return ShadowTexture;
}
public IMaterialFactory GetMaterialFactory()
{
return _materialFactory;
}
private ITextureResourceProvider GetTextureResourceProvider(string relativePath, bool useCache = true)
{
return (_textureCache != null && useCache) ?
@@ -150,6 +164,11 @@ namespace Pal3.Data
return (mv3File, textureProvider);
}
public LgtFile GetLgt(string lgtFilePath)
{
return LgtFileReader.Read(_fileSystem.ReadAllBytes(lgtFilePath));
}
public NavFile GetNav(string sceneFileName, string sceneName)
{
var separator = CpkConstants.DirectorySeparator;
@@ -376,7 +395,7 @@ namespace Pal3.Data
return textures;
}
public Texture2D GetEffectTexture(string name)
public Texture2D GetEffectTexture(string name, out bool hasAlphaChannel)
{
var separator = CpkConstants.DirectorySeparator;
@@ -385,9 +404,7 @@ namespace Pal3.Data
$"{FileConstants.EffectFolderName}{separator}";
ITextureResourceProvider textureProvider = GetTextureResourceProvider(effectFolderRelativePath);
Texture2D effectTexture = textureProvider.GetTexture(name);
Utility.ApplyTransparencyBasedOnColorLuminance(effectTexture);
return effectTexture;
return textureProvider.GetTexture(name, out hasAlphaChannel);
}
public Sprite[] GetEmojiSprites(ActorEmojiType emojiType)
@@ -479,7 +496,7 @@ namespace Pal3.Data
$"Supported video formats are: {string.Join(" ", supportedVideoFormats)}.");
}
public Texture2D[] GetEffectTextures(GraphicsEffect effect, string texturePathFormat)
public (Texture2D texture, bool hasAlphaChannel)[] GetEffectTextures(GraphicsEffect effect, string texturePathFormat)
{
var separator = CpkConstants.DirectorySeparator;
ITextureResourceProvider textureProvider = GetTextureResourceProvider(
@@ -487,19 +504,65 @@ namespace Pal3.Data
if (effect == GraphicsEffect.Fire)
{
var numberOfFrames = EffectConstants.EffectAnimationInfo[effect].NumberOfFrames;
var textures = new Texture2D[numberOfFrames];
var numberOfFrames = EffectConstants.AnimatedFireEffectFrameCount;
var textures = new (Texture2D texture, bool hasAlphaChannel)[numberOfFrames];
for (var i = 0; i < numberOfFrames; i++)
{
var textureNameFormat = Utility.GetFileName(texturePathFormat, separator);
Texture2D texture = textureProvider.GetTexture(string.Format(textureNameFormat, i + 1));
textures[i] = texture;
Texture2D texture = textureProvider.GetTexture(string.Format(textureNameFormat, i + 1), out var hasAlphaChannel);
textures[i] = (texture, hasAlphaChannel);
}
return textures;
}
return Array.Empty<Texture2D>();
return Array.Empty<(Texture2D, bool)>();
}
private string GetVfxPrefabPath(int effectGroupId)
{
return $"Prefabs/VFX/{GameConstants.AppName}/{effectGroupId}";
}
public Object GetVfxEffectPrefab(int effectGroupId)
{
if (_vfxEffectPrefabCache.ContainsKey(effectGroupId))
{
return _vfxEffectPrefabCache[effectGroupId];
}
Object vfxPrefab = Resources.Load(GetVfxPrefabPath(effectGroupId));
if (vfxPrefab != null)
{
_vfxEffectPrefabCache[effectGroupId] = vfxPrefab;
return vfxPrefab;
}
else
{
Debug.LogWarning("VFX prefab not found: " + effectGroupId);
return null;
}
}
public IEnumerator PreLoadVfxEffectAsync(int effectGroupId)
{
if (_vfxEffectPrefabCache.ContainsKey(effectGroupId))
{
yield break;
}
ResourceRequest request = Resources.LoadAsync(GetVfxPrefabPath(effectGroupId));
while (!request.isDone)
{
yield return request;
}
if (request.asset != null)
{
_vfxEffectPrefabCache[effectGroupId] = request.asset;
Debug.Log("VFX prefab preloaded: " + effectGroupId);
}
}
public Texture2D GetCursorTexture()
@@ -529,13 +592,16 @@ namespace Pal3.Data
if (!newSceneCityName.Equals(_currentSceneCityName, StringComparison.OrdinalIgnoreCase))
{
// Clean up cache after exiting current scene block
_textureCache.DisposeAll();
_textureCache?.DisposeAll();
_spriteCache.Clear();
// TODO: Have a better way to manage the lifecycle of pol, mv3, cvd data.
// _polCache.Clear();
// _mv3Cache.Clear();
// _cvdCache.Clear();
// clear all vfx prefabs in cache
_vfxEffectPrefabCache.Clear();
// Unloads assets that are not used (textures etc.)
Resources.UnloadUnusedAssets();
@@ -0,0 +1,18 @@
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
namespace Pal3.Dev
{
using Core.DataReader.Lgt;
using UnityEngine;
/// <summary>
/// LightNode holder component to present LightNode in the Unity inspector.
/// </summary>
public class LightSourceInfoPresenter : MonoBehaviour
{
[SerializeField] public LightNode LightNode;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d762f91c6d264bbba826943e9b1a122b
timeCreated: 1665981881
@@ -13,7 +13,7 @@ namespace Pal3.Dev
/// </summary>
public class MaterialInfoPresenter : MonoBehaviour
{
[SerializeField] public uint blendFlag;
[SerializeField] public GameBoxBlendFlag blendFlag;
[SerializeField] public GameBoxMaterial material;
}
}
+5
View File
@@ -252,6 +252,11 @@ namespace Pal3.Dev
{
new ActorSetNavLayerCommand(-1, 0),
new ActorSetTilePositionCommand(-1, 207, 255)
}},
{ "m20_1_120700", new List<ICommand>()
{
new ActorSetNavLayerCommand(-1, 0),
new ActorSetTilePositionCommand(-1, 72, 48)
}},
{ "m20_2_0", new List<ICommand>()
{
+106
View File
@@ -0,0 +1,106 @@
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
namespace Pal3.Effect
{
using System;
using Data;
using UnityEngine;
using Object = UnityEngine.Object;
public class CombatEffect : MonoBehaviour, IEffect, IDisposable
{
#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 GameObject _effect;
public void Init(GameResourceProvider resourceProvider, uint effectParameter)
{
// Object vfxPrefab = resourceProvider.GetVfxEffectPrefab((int)effectParameter);
//
// if (vfxPrefab != null)
// {
// _effect = (GameObject)Instantiate(vfxPrefab, transform, false);
// _effect.name = "VFX_" + effectParameter;
// }
#if PAL3
if (effectParameter == 465) // 蜀山太极桥特效
#elif PAL3A
if (effectParameter == 160) // 蜀山太极桥特效
#endif
{
_bridgeBaseEffect = gameObject.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 = gameObject.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
{
Object vfxPrefab = resourceProvider.GetVfxEffectPrefab((int)effectParameter);
if (vfxPrefab != null)
{
_effect = (GameObject)Instantiate(vfxPrefab, transform, false);
_effect.name = "VFX_" + effectParameter;
}
}
}
private void OnDisable()
{
Dispose();
}
public void Dispose()
{
if (_bridgeBaseEffect != null)
{
_bridgeBaseEffect.Dispose();
}
if (_bridgeEffect != null)
{
_bridgeEffect.Dispose();
}
if (_effect != null)
{
Destroy(_effect);
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b177a9f780034b4fb51cd37779b44581
timeCreated: 1666332304
+98 -21
View File
@@ -10,20 +10,29 @@ namespace Pal3.Effect
using Command;
using Command.InternalCommands;
using Command.SceCommands;
using Core.GameBox;
using Data;
using MetaData;
using Scene;
using UnityEngine;
using Object = UnityEngine.Object;
public sealed class EffectManager : MonoBehaviour,
public sealed class EffectManager : MonoBehaviour, IDisposable,
ICommandExecutor<EffectPreLoadCommand>,
ICommandExecutor<EffectAttachToActorCommand>,
ICommandExecutor<EffectSetPositionCommand>,
ICommandExecutor<EffectPlayCommand>,
ICommandExecutor<SceneLeavingCurrentSceneNotification>,
ICommandExecutor<ResetGameStateCommand>
{
private GameResourceProvider _resourceProvider;
private SceneManager _sceneManager;
private int _targetActorId = -1;
public void Init(SceneManager sceneManager)
private ICommand _effectPositionCommand;
public void Init(GameResourceProvider resourceProvider,
SceneManager sceneManager)
{
_resourceProvider = resourceProvider ?? throw new ArgumentNullException(nameof(resourceProvider));
_sceneManager = sceneManager ?? throw new ArgumentNullException(nameof(sceneManager));
}
@@ -36,57 +45,125 @@ namespace Pal3.Effect
{
CommandExecutorRegistry<ICommand>.Instance.UnRegister(this);
}
public void Dispose()
{
_effectPositionCommand = null;
}
public void Execute(EffectPreLoadCommand command)
{
// In PAL3A, PreLoad command is always issued right before the effect is played.
// So it is pointless to pre-load the effect here for PAL3A.
#if PAL3
StartCoroutine(_resourceProvider.PreLoadVfxEffectAsync(command.EffectGroupId));
#endif
}
public void Execute(EffectSetPositionCommand command)
{
_effectPositionCommand = command;
}
public void Execute(EffectAttachToActorCommand command)
{
if (command.ActorId == ActorConstants.PlayerActorVirtualID) return;
_targetActorId = command.ActorId;
_effectPositionCommand = command;
}
public void Execute(EffectPlayCommand command)
{
if (_targetActorId == -1) return;
if (_effectPositionCommand == null ||
_sceneManager.GetCurrentScene() is not {} currentScene) return;
#if PAL3A
switch (command.EffectGroupId)
if (_effectPositionCommand is EffectAttachToActorCommand effectAttachToActorCommand)
{
// 南宫煌形态切换为狼形态特效
HandleNanGongHuangTransformEffect(effectAttachToActorCommand, command, currentScene);
}
#endif
// Play VFX
Object vfxPrefab = _resourceProvider.GetVfxEffectPrefab(command.EffectGroupId);
if (vfxPrefab != null)
{
Transform parent = null;
Vector3 localPosition = Vector3.zero;
if (_effectPositionCommand is EffectSetPositionCommand positionCommand &&
_sceneManager.GetSceneRootGameObject() is {} sceneRootGameObject)
{
parent = sceneRootGameObject.transform;
localPosition = GameBoxInterpreter.ToUnityPosition(
new Vector3(positionCommand.X, positionCommand.Y, positionCommand.Z));
}
else if (_effectPositionCommand is EffectAttachToActorCommand actorCommand)
{
parent = currentScene.GetActorGameObject((byte)actorCommand.ActorId).transform;
}
if (parent != null)
{
var vfx = (GameObject)Instantiate(vfxPrefab, parent, false);
vfx.name = "VFX_" + command.EffectGroupId;
vfx.transform.localPosition += localPosition;
}
}
// Play SFX if any
if (EffectConstants.EffectSfxInfo.ContainsKey(command.EffectGroupId))
{
CommandDispatcher<ICommand>.Instance.Dispatch(
new PlaySfxCommand(EffectConstants.EffectSfxInfo[command.EffectGroupId], 1));
}
}
#if PAL3A
private void HandleNanGongHuangTransformEffect(EffectAttachToActorCommand effectAttachToActorCommand,
EffectPlayCommand effectPlayCommand,
Scene currentScene)
{
var actorId = effectAttachToActorCommand.ActorId;
switch (effectPlayCommand.EffectGroupId)
{
// 南宫煌切换为狼妖形态特效
case 164:
{
Scene scene = _sceneManager.GetCurrentScene();
Actor actor = scene.GetActor((byte)_targetActorId);
Actor actor = currentScene.GetActor((byte)actorId);
actor.ChangeName(ActorConstants.NanGongHuangWolfModeActorName);
if (actor.IsActive)
{
var actorActionController = scene.GetActorGameObject((byte)_targetActorId)
var actorActionController = currentScene.GetActorGameObject((byte)actorId)
.GetComponent<ActorActionController>();
actorActionController.PerformAction(actor.GetIdleAction(), overwrite: true);
}
break;
}
// 南宫煌形态切换为人形态特效
// 南宫煌切换为人形态特效
case 315:
{
Scene scene = _sceneManager.GetCurrentScene();
Actor actor = scene.GetActor((byte)_targetActorId);
Actor actor = currentScene.GetActor((byte)actorId);
actor.ChangeName(ActorConstants.NanGongHuangHumanModeActorName);
if (actor.IsActive)
{
var actorActionController = scene.GetActorGameObject((byte)_targetActorId)
var actorActionController = currentScene.GetActorGameObject((byte)actorId)
.GetComponent<ActorActionController>();
actorActionController.PerformAction(actor.GetIdleAction(), overwrite: true);
}
break;
}
}
#endif
_targetActorId = -1;
}
#endif
public void Execute(SceneLeavingCurrentSceneNotification command)
{
Dispose();
}
public void Execute(ResetGameStateCommand command)
{
_targetActorId = -1;
Dispose();
}
}
}
@@ -16,6 +16,7 @@ namespace Pal3.Effect
{
GraphicsEffect.Fire => typeof(FireEffect),
GraphicsEffect.Portal => typeof(PortalEffect),
GraphicsEffect.Combat => typeof(CombatEffect),
_ => null
};
}
+35 -18
View File
@@ -15,21 +15,27 @@ namespace Pal3.Effect
public class FireEffect : MonoBehaviour, IEffect
{
private Texture2D[] _effectTextures = Array.Empty<Texture2D>();
public GameObject EffectGameObject { get; private set; }
public FireEffectType FireEffectType { get; private set; }
private (Texture2D texture, bool hasAlphaChannel)[] _effectTextures = Array.Empty<(Texture2D texture, bool hasAlphaChannel)>();
private AnimatedBillboardRenderer _billboardRenderer;
private PolyModelRenderer _sceneObjectRenderer;
private GameObject _effectGameObject;
private Material _spriteMaterial;
public void Init(GameResourceProvider resourceProvider, uint effectParameter)
{
var fireEffectType = (FireEffectType)effectParameter;
(string TexturePathFormat, string ModelPath, float Size) info = EffectConstants.FireEffectInfo[fireEffectType];
FireEffectType = (FireEffectType)effectParameter;
(string TexturePathFormat, string ModelPath, float Size, float _) info = EffectConstants.FireEffectInfo[FireEffectType];
if (!string.IsNullOrEmpty(info.ModelPath))
{
(Core.DataReader.Pol.PolFile PolFile, ITextureResourceProvider TextureProvider) poly = resourceProvider.GetPol(info.ModelPath);
_sceneObjectRenderer = gameObject.AddComponent<PolyModelRenderer>();
_sceneObjectRenderer.Render(poly.PolFile, poly.TextureProvider, Color.white);
_sceneObjectRenderer.Render(poly.PolFile,
resourceProvider.GetMaterialFactory(),
poly.TextureProvider,
Color.white);
}
if (!string.IsNullOrEmpty(info.TexturePathFormat))
@@ -40,15 +46,13 @@ namespace Pal3.Effect
var sprites = new Sprite[_effectTextures.Length];
for (var i = 0; i < _effectTextures.Length; i++)
{
Texture2D texture = _effectTextures[i];
Texture2D texture = _effectTextures[i].texture;
var sprite = Sprite.Create(texture,
new Rect(0f, 0f, texture.width, texture.height),
new Vector2(0.5f, 0f));
sprites[i] = sprite;
}
var fps = EffectConstants.EffectAnimationInfo[GraphicsEffect.Fire].Fps;
Vector3 parentPosition = transform.position;
var yPosition = parentPosition.y;
@@ -57,18 +61,26 @@ namespace Pal3.Effect
yPosition = _sceneObjectRenderer.GetRendererBounds().max.y;
}
_effectGameObject = new GameObject($"Effect_{GraphicsEffect.Fire.ToString()}");
_effectGameObject.transform.localScale =
EffectGameObject = new GameObject($"Effect_{GraphicsEffect.Fire.ToString()}_{FireEffectType.ToString()}");
EffectGameObject.transform.localScale =
new Vector3(info.Size, info.Size, info.Size);
_effectGameObject.transform.SetParent(gameObject.transform);
_effectGameObject.transform.position = new Vector3(parentPosition.x,
EffectGameObject.transform.SetParent(gameObject.transform);
EffectGameObject.transform.position = new Vector3(parentPosition.x,
yPosition,
parentPosition.z);
_billboardRenderer = _effectGameObject.AddComponent<AnimatedBillboardRenderer>();
StartCoroutine(_billboardRenderer.PlaySpriteAnimation(sprites, fps, -1));
_billboardRenderer = EffectGameObject.AddComponent<AnimatedBillboardRenderer>();
_spriteMaterial = _effectTextures[0].hasAlphaChannel
? null
: resourceProvider.GetMaterialFactory().CreateOpaqueSpriteMaterial();
StartCoroutine(_billboardRenderer.PlaySpriteAnimation(sprites,
EffectConstants.AnimatedFireEffectFrameRate,
-1,
_spriteMaterial));
}
}
private void OnDisable()
{
if (_sceneObjectRenderer != null)
@@ -81,9 +93,14 @@ namespace Pal3.Effect
Destroy(_billboardRenderer);
}
if (_effectGameObject != null)
if (EffectGameObject != null)
{
Destroy(_effectGameObject);
Destroy(EffectGameObject);
}
if (_spriteMaterial != null)
{
Destroy(_spriteMaterial);
}
}
}
+24 -28
View File
@@ -5,11 +5,12 @@
namespace Pal3.Effect
{
using System.Collections;
using System;
using Data;
using UnityEngine;
using Object = UnityEngine.Object;
public class PortalEffect : MonoBehaviour, IEffect
public class PortalEffect : MonoBehaviour, IEffect, IDisposable
{
#if PAL3
private const string PORTAL_BASE_TEXTURE_NAME = "trans.dds";
@@ -20,45 +21,40 @@ namespace Pal3.Effect
private const float PORTAL_DEFAULT_SIZE = 1.3f;
private const float PORTAL_ANIMATION_ROTATION_SPEED = 5f;
private SpriteRenderer _spriteRenderer;
private Coroutine _portalAnimation;
private RotatingSpriteEffect _baseEffect;
private GameObject _rayEffect;
public void Init(GameResourceProvider resourceProvider, uint _)
{
Texture2D baseTexture = resourceProvider.GetEffectTexture(PORTAL_BASE_TEXTURE_NAME);
_spriteRenderer = gameObject.AddComponent<SpriteRenderer>();
_spriteRenderer.sprite = Sprite.Create(baseTexture,
new Rect(0, 0, baseTexture.width, baseTexture.height),
new Vector2(0.5f, 0.5f));
transform.rotation = Quaternion.Euler(90f, 0f, 0f);
transform.localScale =
new Vector3(PORTAL_DEFAULT_SIZE, PORTAL_DEFAULT_SIZE, PORTAL_DEFAULT_SIZE);
_portalAnimation = StartCoroutine(Animate());
}
private IEnumerator Animate()
{
while (isActiveAndEnabled)
_baseEffect = gameObject.AddComponent<RotatingSpriteEffect>();
_baseEffect.Init(resourceProvider,
PORTAL_BASE_TEXTURE_NAME,
new Vector3(PORTAL_DEFAULT_SIZE, PORTAL_DEFAULT_SIZE, PORTAL_DEFAULT_SIZE),
PORTAL_ANIMATION_ROTATION_SPEED);
Object rayEffectPrefab = resourceProvider.GetVfxEffectPrefab(0);
if (rayEffectPrefab != null)
{
var rotationDelta = PORTAL_ANIMATION_ROTATION_SPEED * Time.deltaTime;
gameObject.transform.localRotation *= Quaternion.Euler(0f, 0f, -rotationDelta);
yield return null;
_rayEffect = (GameObject)Instantiate(rayEffectPrefab, transform, false);
_rayEffect.name = "VFX_0";
}
}
private void OnDisable()
{
if (_portalAnimation != null)
Dispose();
}
public void Dispose()
{
if (_baseEffect != null)
{
StopCoroutine(_portalAnimation);
_baseEffect.Dispose();
}
if (_spriteRenderer != null)
if (_rayEffect != null)
{
Destroy(_spriteRenderer);
Destroy(_rayEffect);
}
}
}
@@ -1,88 +0,0 @@
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
namespace Pal3.Effect
{
using System;
using Command;
using Command.InternalCommands;
using Command.SceCommands;
using UnityEngine;
using UnityEngine.Rendering.PostProcessing;
public sealed class PostProcessManager : MonoBehaviour,
ICommandExecutor<EffectSetScreenEffectCommand>,
ICommandExecutor<ResetGameStateCommand>
{
private PostProcessVolume _postProcessVolume;
private PostProcessLayer _postProcessLayer;
private int _currentAppliedEffectMode = -1;
public void Init(PostProcessVolume volume,
PostProcessLayer postProcessLayer)
{
_postProcessVolume = volume != null ? volume : throw new ArgumentNullException(nameof(volume));
_postProcessLayer = postProcessLayer != null ? postProcessLayer : throw new ArgumentNullException(nameof(postProcessLayer));
}
private void OnEnable()
{
CommandExecutorRegistry<ICommand>.Instance.Register(this);
}
private void OnDisable()
{
CommandExecutorRegistry<ICommand>.Instance.UnRegister(this);
}
public int GetCurrentAppliedEffectMode()
{
return _currentAppliedEffectMode;
}
public void Execute(EffectSetScreenEffectCommand command)
{
switch (command.Mode)
{
// Disable all post-processing effects
case -1:
{
_postProcessLayer.enabled = false;
if (_postProcessVolume.profile.TryGetSettings(out ColorGrading colorAdjustments))
{
colorAdjustments.active = false;
}
if (_postProcessVolume.profile.TryGetSettings(out Vignette vignette))
{
vignette.active = false;
}
break;
}
// Vintage + color filter effect
case 1:
{
if (_postProcessVolume.profile.TryGetSettings(out ColorGrading colorAdjustments))
{
colorAdjustments.active = true;
}
if (_postProcessVolume.profile.TryGetSettings(out Vignette vignette))
{
vignette.active = true;
}
_postProcessLayer.enabled = true;
break;
}
}
_currentAppliedEffectMode = command.Mode;
}
public void Execute(ResetGameStateCommand command)
{
Execute(new EffectSetScreenEffectCommand(-1));
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: dd6bbdf7bf441b346b757f455bc3deac
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,49 @@
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
namespace Pal3.Effect.PostProcessing
{
using System;
using UnityEngine;
using UnityEngine.Rendering.PostProcessing;
[Serializable]
[PostProcess(typeof(DistortionRenderer), PostProcessEvent.AfterStack, "Pal3/Distortion")]
public sealed class Distortion : PostProcessEffectSettings
{
[Range(0.1f, 30.0f), Tooltip("TimeScale")]
public FloatParameter timeScale = new() { value = 4.0f };
[Range(0.1f, 30.0f), Tooltip("X Factor")]
public FloatParameter xFactor = new() { value = 15.0f };
[Range(0.1f, 30.0f), Tooltip("Y Factor")]
public FloatParameter yFactor = new() { value = 10.0f };
}
public sealed class DistortionRenderer : PostProcessEffectRenderer<Distortion>
{
private static readonly int TimeScalePropertyId = Shader.PropertyToID("_TimeScale");
private static readonly int XFactorPropertyId = Shader.PropertyToID("_XFactor");
private static readonly int YFactorPropertyId = Shader.PropertyToID("_YFactor");
private Shader _distortionShader;
public override void Init()
{
_distortionShader = Shader.Find("Pal3/PostEffectDistortion");
base.Init();
}
public override void Render(PostProcessRenderContext context)
{
PropertySheet sheet = context.propertySheets.Get(_distortionShader);
sheet.properties.SetFloat(TimeScalePropertyId, settings.timeScale);
sheet.properties.SetFloat(XFactorPropertyId, settings.xFactor);
sheet.properties.SetFloat(YFactorPropertyId, settings.yFactor);
context.command.BlitFullscreenTriangle(context.source, context.destination, sheet, 0);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: bb4ad18ac69b12845a429aba13929a07
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,130 @@
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
namespace Pal3.Effect.PostProcessing
{
using System;
using Command;
using Command.InternalCommands;
using Command.SceCommands;
using Core.Utils;
using UnityEngine;
using UnityEngine.Rendering.PostProcessing;
public sealed class PostProcessManager : MonoBehaviour,
ICommandExecutor<EffectSetScreenEffectCommand>,
ICommandExecutor<ResetGameStateCommand>
{
private PostProcessVolume _postProcessVolume;
private PostProcessLayer _postProcessLayer;
private Bloom _bloom;
private AmbientOcclusion _ambientOcclusion;
private ColorGrading _colorGrading;
private Vignette _vignette;
private Distortion _distortion;
private int _currentAppliedEffectMode = -1;
public void Init(PostProcessVolume volume,
PostProcessLayer postProcessLayer)
{
_postProcessVolume = volume != null ? volume : throw new ArgumentNullException(nameof(volume));
_postProcessLayer = postProcessLayer != null ? postProcessLayer : throw new ArgumentNullException(nameof(postProcessLayer));
_bloom = _postProcessVolume.profile.GetSetting<Bloom>();
#if RTX_ON
_bloom.active = false; // Pointless when lighting is on
#else
_bloom.active = Utility.IsDesktopDevice(); // Enable bloom for better VFX visual fidelity on desktop devices
#endif
_ambientOcclusion = _postProcessVolume.profile.GetSetting<AmbientOcclusion>();
#if RTX_ON && !UNITY_ANDROID // AO not working well with OpenGL on Android
_ambientOcclusion.active = Utility.IsDesktopDevice(); // Enable AmbientOcclusion for better visual fidelity on desktop devices
#else
_ambientOcclusion.active = false; // Pointless when lighting is off
#endif
_colorGrading = _postProcessVolume.profile.GetSetting<ColorGrading>();
_colorGrading.active = false;
_vignette = _postProcessVolume.profile.GetSetting<Vignette>();
_vignette.active = false;
_distortion = _postProcessVolume.profile.GetSetting<Distortion>();
_distortion.active = false;
TogglePostProcessLayerWhenNeeded();
}
private void TogglePostProcessLayerWhenNeeded()
{
if (_bloom.active ||
_ambientOcclusion.active ||
_colorGrading.active ||
_vignette.active ||
_distortion.active)
{
_postProcessLayer.enabled = true;
}
else
{
_postProcessLayer.enabled = false;
}
}
private void OnEnable()
{
CommandExecutorRegistry<ICommand>.Instance.Register(this);
}
private void OnDisable()
{
CommandExecutorRegistry<ICommand>.Instance.UnRegister(this);
}
public int GetCurrentAppliedEffectMode()
{
return _currentAppliedEffectMode;
}
public void Execute(EffectSetScreenEffectCommand command)
{
switch (command.Mode)
{
// Disable all post-processing effects used by the game
case -1:
{
_colorGrading.active = false;
_vignette.active = false;
_distortion.active = false;
break;
}
// Distortion effect
case 0:
{
_distortion.active = true;
break;
}
// Vintage + color filter effect
case 1:
{
_colorGrading.active = true;
_vignette.active = true;
break;
}
}
_currentAppliedEffectMode = command.Mode;
TogglePostProcessLayerWhenNeeded();
}
public void Execute(ResetGameStateCommand command)
{
Execute(new EffectSetScreenEffectCommand(-1));
}
}
}
@@ -0,0 +1,91 @@
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
namespace Pal3.Effect
{
using System;
using Data;
using System.Collections;
using UnityEngine;
public class RotatingSpriteEffect : MonoBehaviour, IDisposable
{
private GameObject _root;
private SpriteRenderer _spriteRenderer;
private Material _material;
private Coroutine _animation;
private float _rotationSpeed;
public void Init(GameResourceProvider resourceProvider,
string textureName,
Vector3 scale,
float rotationSpeed)
{
_rotationSpeed = rotationSpeed;
Texture2D texture = resourceProvider.GetEffectTexture(textureName, out var hasAlphaChannel);
_root = new GameObject($"RotatingSpriteEffect_{textureName}");
_root.transform.SetParent(transform, false);
_spriteRenderer = _root.AddComponent<SpriteRenderer>();
_spriteRenderer.sprite = Sprite.Create(texture,
new Rect(0, 0, texture.width, texture.height),
new Vector2(0.5f, 0.5f));
if (!hasAlphaChannel)
{
_material = resourceProvider.GetMaterialFactory().CreateOpaqueSpriteMaterial(texture);
_spriteRenderer.sharedMaterial = _material;
}
Quaternion parentRotation = gameObject.transform.rotation;
_root.transform.localRotation = Quaternion.Euler(parentRotation.x + 90f, 0f, 0f);
_root.transform.localScale = scale;
_animation = StartCoroutine(Animate());
}
private IEnumerator Animate()
{
while (isActiveAndEnabled)
{
var rotationDelta = _rotationSpeed * Time.deltaTime;
_root.transform.localRotation *= Quaternion.Euler(0f, 0f, -rotationDelta);
yield return null;
}
}
private void OnDisable()
{
Dispose();
}
public void Dispose()
{
if (_animation != null)
{
StopCoroutine(_animation);
}
if (_material != null)
{
Destroy(_material);
}
if (_spriteRenderer != null)
{
Destroy(_spriteRenderer);
}
if (_root != null)
{
Destroy(_root);
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 10c2b48514804783bc35a3b045455dd8
timeCreated: 1666333743
@@ -18,6 +18,7 @@ namespace Pal3
using Core.Utils;
using Data;
using MetaData;
using Renderer;
using TMPro;
using UnityEditor;
using UnityEngine;
@@ -123,7 +124,14 @@ namespace Pal3
ServiceLocator.Instance.Register<ITextureLoaderFactory>(textureLoaderFactory);
// Init Game resource provider
var resourceProvider = new GameResourceProvider(cpkFileSystem, new TextureLoaderFactory(), codepage);
var resourceProvider = new GameResourceProvider(cpkFileSystem,
new TextureLoaderFactory(),
#if RTX_ON
new ToonMaterialFactory(),
#else
new LegacyMaterialFactory(),
#endif
codepage);
ServiceLocator.Instance.Register(resourceProvider);
// Instantiate starting component
@@ -0,0 +1,35 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: c46f07b5ed07e4e92aa78254188d3d10, type: 3}
m_Name: InputSystem.inputsettings
m_EditorClassIdentifier:
m_SupportedDevices: []
m_UpdateMode: 1
m_MaxEventBytesPerUpdate: 5242880
m_MaxQueuedEventsPerUpdate: 1000
m_CompensateForScreenOrientation: 1
m_BackgroundBehavior: 0
m_EditorInputBehaviorInPlayMode: 0
m_DefaultDeadzoneMin: 0.15
m_DefaultDeadzoneMax: 0.975
m_DefaultButtonPressPoint: 0.5
m_ButtonReleaseThreshold: 0.75
m_DefaultTapTime: 0.2
m_DefaultSlowTapTime: 0.5
m_DefaultHoldTime: 0.4
m_TapRadius: 5
m_MultiTapDelayTime: 0.75
m_DisableRedundantEventsMerging: 0
m_iOSSettings:
m_MotionUsage:
m_Enabled: 0
m_Description:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d36b5fde9d421c74cba9317a109723a2
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:
@@ -290,7 +290,7 @@ namespace Pal3.Input
""id"": ""0968cb64-8274-4260-9c62-9cba759ca4ab"",
""path"": ""<Gamepad>/leftStick"",
""interactions"": """",
""processors"": """",
""processors"": ""StickDeadzone"",
""groups"": """",
""action"": ""Movement"",
""isComposite"": false,
@@ -301,7 +301,7 @@ namespace Pal3.Input
""id"": ""0eba8dc6-2c21-41f6-8318-572955eeb71a"",
""path"": ""<Joystick>/stick"",
""interactions"": """",
""processors"": """",
""processors"": ""StickDeadzone"",
""groups"": """",
""action"": ""Movement"",
""isComposite"": false,
@@ -356,7 +356,7 @@ namespace Pal3.Input
""id"": ""795b72b8-65f9-49bb-a352-a15e10c7b261"",
""path"": ""<Gamepad>/rightStick/right"",
""interactions"": """",
""processors"": """",
""processors"": ""AxisDeadzone"",
""groups"": """",
""action"": ""RotateCameraClockwise"",
""isComposite"": false,
@@ -378,7 +378,7 @@ namespace Pal3.Input
""id"": ""9c8591f6-45f7-4061-9ce9-3cf253dece26"",
""path"": ""<Gamepad>/rightStick/left"",
""interactions"": """",
""processors"": """",
""processors"": ""AxisDeadzone"",
""groups"": """",
""action"": ""RotateCameraCounterClockwise"",
""isComposite"": false,
@@ -266,7 +266,7 @@
"id": "0968cb64-8274-4260-9c62-9cba759ca4ab",
"path": "<Gamepad>/leftStick",
"interactions": "",
"processors": "",
"processors": "StickDeadzone",
"groups": "",
"action": "Movement",
"isComposite": false,
@@ -277,7 +277,7 @@
"id": "0eba8dc6-2c21-41f6-8318-572955eeb71a",
"path": "<Joystick>/stick",
"interactions": "",
"processors": "",
"processors": "StickDeadzone",
"groups": "",
"action": "Movement",
"isComposite": false,
@@ -332,7 +332,7 @@
"id": "795b72b8-65f9-49bb-a352-a15e10c7b261",
"path": "<Gamepad>/rightStick/right",
"interactions": "",
"processors": "",
"processors": "AxisDeadzone",
"groups": "",
"action": "RotateCameraClockwise",
"isComposite": false,
@@ -354,7 +354,7 @@
"id": "9c8591f6-45f7-4061-9ce9-3cf253dece26",
"path": "<Gamepad>/rightStick/left",
"interactions": "",
"processors": "",
"processors": "AxisDeadzone",
"groups": "",
"action": "RotateCameraCounterClockwise",
"isComposite": false,
@@ -244,7 +244,7 @@ namespace Pal3.MetaData
{ "102", "WCA" },
{ "104", "WXF" },
{ "105", "WLF" },
{ "107", "WZF" },
{ "107", "WZC" },
};
#elif PAL3A
public static readonly Dictionary<string, string> MainActorWeaponMap = new()
+79 -24
View File
@@ -32,6 +32,10 @@ namespace Pal3.MetaData
public static class EffectConstants
{
public const int AnimatedFireEffectFrameCount = 16;
public const int AnimatedFireEffectFrameRate = 10;
private static readonly char PathSeparator = CpkConstants.DirectorySeparator;
private static readonly string EffectScnRelativePath =
@@ -39,57 +43,108 @@ namespace Pal3.MetaData
$"{FileConstants.EffectScnFolderName}{PathSeparator}";
#if PAL3
public static readonly Dictionary<FireEffectType, (string TexturePathFormat, string ModelPath, float Size)>
public static readonly Dictionary<FireEffectType, (string TexturePathFormat, string ModelPath, float Size, float lightSourceYOffset)>
FireEffectInfo = new()
{
{FireEffectType.Type1, new (
EffectScnRelativePath + "Fire1" + PathSeparator + "torch{0:00}.tga",
"", 3.3f) },
"", 3.3f, 0.5f) },
{FireEffectType.Type2, new (
EffectScnRelativePath + "Fire2" + PathSeparator + "huo{0:00}.tga",
"", 1f) },
EffectScnRelativePath + "Fire2" + PathSeparator + "{0:00}.tga",
"", 1f, 0.2f) },
{FireEffectType.Type3, new (
EffectScnRelativePath + "Candle" + PathSeparator + "{0:000}.tga",
$"{EffectScnRelativePath}Candle{PathSeparator}candle.pol", 1f) },
$"{EffectScnRelativePath}Candle{PathSeparator}candle.pol", 1f, 0.2f) },
{FireEffectType.Type4, new (
EffectScnRelativePath + "Fire4" + PathSeparator + "{0:000}.tga",
"", 5.8f) },
EffectScnRelativePath + "Fire4" + PathSeparator + "{0:00}.tga",
"", 5.8f, 0.5f) },
{FireEffectType.Type5, new (
EffectScnRelativePath + "Candle" + PathSeparator + "{0:000}.tga",
$"{EffectScnRelativePath}Lamp{PathSeparator}lamp.pol", 0.7f) },
$"{EffectScnRelativePath}Lamp{PathSeparator}lamp.pol", 0.7f, 0.2f) },
};
#elif PAL3A
public static readonly Dictionary<FireEffectType, (string TexturePathFormat, string ModelPath, float Size)>
public static readonly Dictionary<FireEffectType, (string TexturePathFormat, string ModelPath, float Size, float lightSourceYOffset)>
FireEffectInfo = new()
{
{FireEffectType.Type1, new (
EffectScnRelativePath + "Fire4" + PathSeparator + "{0:000}.tga",
"", 5.8f) },
EffectScnRelativePath + "Fire4" + PathSeparator + "{0:00}.tga",
"", 5.8f, 0.5f) },
{FireEffectType.Type2, new (
EffectScnRelativePath + "Fire1" + PathSeparator + "torch{0:00}.tga",
"", 3.3f) },
"", 3.3f, 0.5f) },
{FireEffectType.Type3, new (
EffectScnRelativePath + "Candle" + PathSeparator + "{0:000}.tga",
$"{EffectScnRelativePath}Lamp{PathSeparator}lamp.pol", 0.7f) },
$"{EffectScnRelativePath}Lamp{PathSeparator}lamp.pol", 0.7f, 0.2f) },
{FireEffectType.Type4, new (
EffectScnRelativePath + "Candle" + PathSeparator + "{0:000}.tga",
$"{EffectScnRelativePath}Candle{PathSeparator}candle.pol", 1f) },
$"{EffectScnRelativePath}Candle{PathSeparator}candle.pol", 1f, 0.2f) },
{FireEffectType.Type5, new (
EffectScnRelativePath + "Fire2" + PathSeparator + "huo{0:00}.tga",
"", 1f) },
EffectScnRelativePath + "Fire2" + PathSeparator + "{0:00}.tga",
"", 1f, 0.3f) },
{FireEffectType.Type6, new (
EffectScnRelativePath + "Candle" + PathSeparator + "{0:000}.tga",
"", 1f) },
"", 1f, 0.6f) },
};
#endif
public static readonly Dictionary<GraphicsEffect, (int NumberOfFrames, int Fps)> EffectAnimationInfo = new()
#if PAL3
// Effect group id to sfx mapping
public static readonly Dictionary<int, string> EffectSfxInfo = new()
{
{GraphicsEffect.PoisonFog, new (0, 0) },
{GraphicsEffect.Portal, new (0, 0)},
{GraphicsEffect.SavePoint, new (0, 0)},
{GraphicsEffect.Fire, new (16, 10)},
{GraphicsEffect.Combat, new (0, 0)},
{ 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
}
}
@@ -0,0 +1,64 @@
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
namespace Pal3.MetaData
{
using System.Collections.Generic;
using UnityEngine;
public static class LightingConstants
{
/// <summary>
/// This is the lighting color override for the target scene city.
/// </summary>
#if PAL3
public static readonly Dictionary<string, Color> MainLightColorInfoGlobal = new()
{
{ "q13", new Color(40f / 255f, 80f / 255f, 200f / 255f) }, // 酆都
{ "q14", new Color(100f / 255f, 100f / 255f, 200f / 255f) }, // 鬼界外围
{ "m24", new Color(30f / 255f, 80f / 255f, 200f / 255f) }, // 剑冢
};
#elif PAL3A
public static readonly Dictionary<string, Color> MainLightColorInfoGlobal = new()
{
{ "m02", new Color(10f / 255f, 30f / 255f, 60f / 255f) }, // 地脉门户
{ "m15", new Color(80f / 255f, 130f / 255f, 200f / 255f) }, // 月光城
};
#endif
/// <summary>
/// This is the lighting color override for the target scene.
/// </summary>
#if PAL3
public static readonly Dictionary<string, Color> MainLightColorInfo = new()
{
{ "q02_n14_0", new Color(75f / 255f, 75f / 255f, 75f / 255f) }, // 地牢1
{ "q02_n16_0", new Color(30f / 255f, 30f / 255f, 30f / 255f) }, // 地牢2
{ "q07_q07a_1", new Color(120f / 255f, 50f / 255f, 30f / 255f) }, // 安宁村黄昏
{ "m06_4_-1", new Color(0f / 255f, 0f / 255f, 80f / 255f) }, // 蓬莱密道
};
#elif PAL3A
public static readonly Dictionary<string, Color> MainLightColorInfo = new()
{
};
#endif
/// <summary>
/// This is the lighting color override for the target scene.
/// </summary>
#if PAL3
public static readonly Dictionary<string, Quaternion> MainLightRotationInfo = new()
{
{ "q01_yn01a_1", Quaternion.Euler(130f, 40f, 0f) }, // 重楼当剑
{ "q07_q07a_1", Quaternion.Euler(145f, 50f, 0f) }, // 安宁村黄昏
{ "m06_1_-1", Quaternion.Euler(30f, -50f, 0f) }, // 蓬莱码头
};
#elif PAL3A
public static readonly Dictionary<string, Quaternion> MainLightRotationInfo = new()
{
};
#endif
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 03dddc6562c848f89cd31108593bc9c6
timeCreated: 1667264178
+23 -27
View File
@@ -5,17 +5,12 @@
namespace Pal3
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Actor;
using Audio;
using Camera;
using Command;
using Command.InternalCommands;
using Command.SceCommands;
using Core.DataReader.Scn;
using Core.FileSystem;
using Core.Services;
@@ -26,10 +21,6 @@ namespace Pal3
using Feature;
using Input;
using IngameDebugConsole;
using MetaData;
#if PAL3
using MiniGame;
#endif
using Player;
using Scene;
using Script;
@@ -43,8 +34,12 @@ namespace Pal3
using UnityEngine.UI;
using UnityEngine.Video;
using Video;
using PostProcessManager = Effect.PostProcessManager;
using PostProcessManager = Effect.PostProcessing.PostProcessManager;
#if PAL3
using MiniGame;
#endif
/// <summary>
/// Pal3 game model
/// </summary>
@@ -279,7 +274,7 @@ namespace Pal3
ServiceLocator.Instance.Register(_postProcessManager);
_effectManager = gameObject.AddComponent<EffectManager>();
_effectManager.Init(_sceneManager);
_effectManager.Init(_gameResourceProvider, _sceneManager);
ServiceLocator.Instance.Register(_effectManager);
_saveManager = new SaveManager(_sceneManager,
@@ -314,10 +309,10 @@ namespace Pal3
DebugLogManager.Instance.OnLogWindowShown += OnDebugWindowShown;
DebugLogManager.Instance.OnLogWindowHidden += OnDebugWindowHidden;
DebugLogConsole.AddCommand("vars", "List current global variables.", ListCurrentGlobalVariables);
DebugLogConsole.AddCommand("save", "Save game state into executable commands.", ConvertCurrentGameStateToCommandStr);
DebugLogConsole.AddCommand("info", "Get current game info.", GetCurrentGameInfo);
DebugLogConsole.AddCommand("state", "Get current game state in commands form.", PrintCurrentGameStateInCommandsForm);
DebugLogConsole.AddCommand("info", "Get current game info.", PrintCurrentGameInfo);
DebugLogConsole.AddCommand<int>("fps", "Set target FPS.", SetTargetFps);
DisableInGameDebugConsoleButtonNavigation();
@@ -342,7 +337,7 @@ namespace Pal3
_touchControlUIManager.Dispose();
_favorManager.Dispose();
_mazeSkipper.Dispose();
#if PAL3
_appraisalsMiniGame.Dispose();
_sailingMiniGame.Dispose();
@@ -409,21 +404,22 @@ namespace Pal3
}
}
private string ConvertCurrentGameStateToCommandStr()
private void PrintCurrentGameStateInCommandsForm()
{
var commands = _saveManager.ConvertCurrentGameStateToCommands(SaveLevel.Minimal);
return commands == null ? null : string.Join('\n', commands.Select(CommandExtensions.ToString).ToList());
var state = commands == null ? null : string.Join('\n', commands.Select(CommandExtensions.ToString).ToList());
Debug.Log(state + '\n');
}
private string GetCurrentGameInfo()
private void PrintCurrentGameInfo()
{
if (_sceneManager.GetCurrentScene() is not { } currentScene) return null;
if (_sceneManager.GetCurrentScene() is not { } currentScene) return;
var info = new StringBuilder();
ScnSceneInfo currentSceneInfo = currentScene.GetSceneInfo();
info.Append($"Current scene: {currentSceneInfo.CityName} {currentSceneInfo.Name}\n");
info.Append($"Current scene: {currentSceneInfo.ToString()}\n");
var playerActorMovementController = currentScene
.GetActorGameObject((byte) _playerManager.GetPlayerActor()).GetComponent<ActorMovementController>();
@@ -431,15 +427,15 @@ namespace Pal3
info.Append($"Player actor current nav layer: {playerActorMovementController.GetCurrentLayerIndex()} " +
$"tile position: {playerActorMovementController.GetTilePosition()}\n");
return info.ToString();
info.Append(_scriptManager.GetGlobalVariables()
.Aggregate("Global vars: ", (current, variable) => current + $"{variable.Key}: {variable.Value} "));
Debug.Log(info.ToString() + '\n');
}
private string ListCurrentGlobalVariables()
private void SetTargetFps(int targetFps)
{
if (_scriptManager.GetGlobalVariables() is not { Count: > 0 }) return null;
return _scriptManager.GetGlobalVariables()
.Aggregate("Global vars: ", (current, variable) => current + $"{variable.Key}: {variable.Value} ");
Application.targetFrameRate = targetFps;
}
}
}
@@ -408,12 +408,15 @@ namespace Pal3.Player
if (!Physics.Raycast(ray, out RaycastHit hit)) return;
var layerIndex = _sceneManager.GetCurrentScene().GetMeshColliders().FirstOrDefault(
c => c.Value.Contains(hit.collider)).Key;
var layerIndex = _sceneManager.GetCurrentScene()
.GetMeshColliders()
.FirstOrDefault(_ => _.Value == hit.collider)
.Key;
_playerActorMovementController.PortalToPosition(hit.point, layerIndex);
}
// Raycast caches to avoid GC
private readonly RaycastHit[] _raycastHits = new RaycastHit[4];
private readonly Dictionary<int, Vector3> _tapPoints = new ();
private void MoveToTapPosition(bool isDoubleTap)
@@ -432,8 +435,7 @@ namespace Pal3.Player
for (var i = 0; i < hitCount; i++)
{
RaycastHit hit = _raycastHits[i];
var layerIndex = meshColliders.FirstOrDefault(
c => c.Value.Contains(hit.collider)).Key;
var layerIndex = meshColliders.FirstOrDefault(_ => _.Value == hit.collider).Key;
Vector2Int tilePosition = tilemap.GetTilePosition(hit.point, layerIndex);
if (!tilemap.IsTilePositionInsideTileMap(tilePosition, layerIndex)) continue;
@@ -30,19 +30,18 @@ namespace Pal3.Renderer
private float _animationDuration;
private Coroutine _animation;
private CancellationTokenSource _animationCts;
private const float TRANSPARENT_THRESHOLD = 1.0f;
private readonly int _mainTexturePropertyId = Shader.PropertyToID("_MainTex");
private readonly int _cutoffPropertyId = Shader.PropertyToID("_Cutoff");
private readonly int _tintColorPropertyId = Shader.PropertyToID("_TintColor");
private Shader _standardNoShadowShader;
public void Init(CvdFile cvdFile, ITextureResourceProvider textureProvider, Color tintColor, float time)
public void Init(CvdFile cvdFile,
IMaterialFactory materialFactory,
ITextureResourceProvider textureProvider,
Color tintColor,
float time)
{
_animationDuration = cvdFile.AnimationDuration;
_tintColor = tintColor;
_standardNoShadowShader = Shader.Find("Pal3/StandardNoShadow");
foreach (CvdGeometryNode node in cvdFile.RootNodes)
{
BuildTextureCache(node, textureProvider, _textureCache);
@@ -58,6 +57,7 @@ namespace Pal3.Renderer
hashKey,
cvdFile.RootNodes[i],
_textureCache,
materialFactory,
root);
}
@@ -110,17 +110,17 @@ namespace Pal3.Renderer
private Matrix4x4 GetFrameMatrix(float time, CvdGeometryNode node)
{
Vector3 position = GetPosition(time, node.PositionKeyInfos);
GameBoxQuaternion rotation = GetRotation(time, node.RotationKeyInfos);
(Vector3 scale, GameBoxQuaternion scaleRotation) = GetScale(time, node.ScaleKeyInfos);
Quaternion rotation = GetRotation(time, node.RotationKeyInfos);
(Vector3 scale, Quaternion scaleRotation) = GetScale(time, node.ScaleKeyInfos);
Quaternion scalePreRotation = GameBoxInterpreter.CvdQuaternionToUnityQuaternion(scaleRotation);
Quaternion scalePreRotation = scaleRotation;
Quaternion scaleInverseRotation = Quaternion.Inverse(scalePreRotation);
return Matrix4x4.Translate(GameBoxInterpreter.CvdPositionToUnityPosition(position))
return Matrix4x4.Translate(position)
* Matrix4x4.Scale(new Vector3(node.Scale, node.Scale, node.Scale))
* Matrix4x4.Rotate(GameBoxInterpreter.CvdQuaternionToUnityQuaternion(rotation))
* Matrix4x4.Rotate(rotation)
* Matrix4x4.Rotate(scalePreRotation)
* Matrix4x4.Scale(GameBoxInterpreter.CvdScaleToUnityScale(scale))
* Matrix4x4.Scale(scale)
* Matrix4x4.Rotate(scaleInverseRotation);
}
@@ -129,6 +129,7 @@ namespace Pal3.Renderer
string meshName,
CvdGeometryNode node,
Dictionary<string, Texture2D> textureCache,
IMaterialFactory materialFactory,
GameObject parent)
{
var meshObject = new GameObject(meshName);
@@ -161,7 +162,7 @@ namespace Pal3.Renderer
NormalBuffer = new Vector3[meshSection.FrameVertices[frameIndex].Length],
UvBuffer = new Vector2[meshSection.FrameVertices[frameIndex].Length],
};
UpdateMeshDataBuffer(ref meshDataBuffer,
meshSection,
frameIndex,
@@ -180,27 +181,26 @@ namespace Pal3.Renderer
materialInfoPresenter.material = meshSection.Material;
#endif
Material[] materials = materialFactory.CreateStandardMaterials(
textureCache[meshSection.TextureName],
shadowTexture: null, // CVD models don't have shadow textures
_tintColor,
meshSection.BlendFlag,
TRANSPARENT_THRESHOLD);
var meshRenderer = meshSectionObject.AddComponent<StaticMeshRenderer>();
var material = new Material(_standardNoShadowShader);
material.SetTexture(_mainTexturePropertyId, textureCache[meshSection.TextureName]);
var cutoff = (meshSection.BlendFlag == 1) ? 0.3f : 0f;
if (cutoff > Mathf.Epsilon)
{
material.SetFloat(_cutoffPropertyId, cutoff);
}
material.SetColor(_tintColorPropertyId, _tintColor);
var triangles = GameBoxInterpreter.ToUnityTriangles(meshSection.Triangles);
Mesh renderMesh = meshRenderer.Render(ref meshDataBuffer.VertexBuffer,
ref triangles,
Mesh renderMesh = meshRenderer.Render(
ref meshDataBuffer.VertexBuffer,
ref meshSection.Triangles,
ref meshDataBuffer.NormalBuffer,
ref meshDataBuffer.UvBuffer,
ref material,
ref meshDataBuffer.UvBuffer,
ref materials,
true);
renderMesh.RecalculateNormals();
renderMesh.RecalculateTangents();
nodeMeshes.Item2[i] = new RenderMeshComponent
{
Mesh = renderMesh,
@@ -217,7 +217,12 @@ namespace Pal3.Renderer
for (var i = 0; i < node.Children.Length; i++)
{
var childMeshName = $"{meshName}-{i}";
RenderMeshInternal(time, childMeshName, node.Children[i], textureCache, meshObject);
RenderMeshInternal(time,
childMeshName,
node.Children[i],
textureCache,
materialFactory,
meshObject);
}
}
@@ -233,9 +238,7 @@ namespace Pal3.Renderer
{
for (var i = 0; i < frameVertices.Length; i++)
{
meshDataBuffer.VertexBuffer[i] = matrix.MultiplyPoint3x4(
GameBoxInterpreter.CvdPositionToUnityPosition(frameVertices[i].Position));
meshDataBuffer.NormalBuffer[i] = GameBoxInterpreter.CvdPositionToUnityPosition(frameVertices[i].Normal);
meshDataBuffer.VertexBuffer[i] = matrix.MultiplyPoint3x4(frameVertices[i].Position);
meshDataBuffer.UvBuffer[i] = frameVertices[i].Uv;
}
}
@@ -245,8 +248,7 @@ namespace Pal3.Renderer
{
var toFrameVertices = meshSection.FrameVertices[frameIndex + 1];
Vector3 lerpPosition = Vector3.Lerp(frameVertices[i].Position, toFrameVertices[i].Position, influence);
meshDataBuffer.VertexBuffer[i] = matrix.MultiplyPoint3x4(GameBoxInterpreter.CvdPositionToUnityPosition(lerpPosition));
// Ignoring normals here since Unity can help us do the calculation.
meshDataBuffer.VertexBuffer[i] = matrix.MultiplyPoint3x4(lerpPosition);
Vector2 lerpUv = Vector2.Lerp(frameVertices[i].Uv, toFrameVertices[i].Uv, influence);
meshDataBuffer.UvBuffer[i] = lerpUv;
}
@@ -287,8 +289,6 @@ namespace Pal3.Renderer
renderMeshComponent.Mesh.vertices = meshDataBuffer.VertexBuffer;
renderMeshComponent.Mesh.uv = meshDataBuffer.UvBuffer;
renderMeshComponent.Mesh.RecalculateBounds();
//renderMeshComponent.Mesh.RecalculateNormals();
//renderMeshComponent.Mesh.RecalculateTangents();
}
}
}
@@ -379,7 +379,7 @@ namespace Pal3.Renderer
return nodePositionInfo[^1].Position;
}
private (Vector3 Scale, GameBoxQuaternion Rotation) GetScale(float time,
private (Vector3 Scale, Quaternion Rotation) GetScale(float time,
CvdAnimationScaleKeyFrame[] nodeScaleInfo)
{
if (nodeScaleInfo.Length == 1)
@@ -398,23 +398,10 @@ namespace Pal3.Renderer
var influence = (time - fromKeyFrame.Time) /
(toKeyFrame.Time - fromKeyFrame.Time);
Quaternion calculatedRotation = Quaternion.Lerp(
new Quaternion(fromKeyFrame.Rotation.X,
fromKeyFrame.Rotation.Y,
fromKeyFrame.Rotation.Z,
fromKeyFrame.Rotation.W),
new Quaternion(toKeyFrame.Rotation.X,
toKeyFrame.Rotation.Y,
toKeyFrame.Rotation.Z,
toKeyFrame.Rotation.W),
fromKeyFrame.Rotation,
toKeyFrame.Rotation,
influence);
return (Vector3.Lerp(fromKeyFrame.Scale, toKeyFrame.Scale, influence),
new GameBoxQuaternion()
{
X = calculatedRotation.x,
Y = calculatedRotation.y,
Z = calculatedRotation.z,
W = calculatedRotation.w,
});
return (Vector3.Lerp(fromKeyFrame.Scale, toKeyFrame.Scale, influence), calculatedRotation);
}
}
@@ -422,7 +409,7 @@ namespace Pal3.Renderer
return (lastKeyFrame.Scale, lastKeyFrame.Rotation);
}
private GameBoxQuaternion GetRotation(float time,
private Quaternion GetRotation(float time,
CvdAnimationRotationKeyFrame[] nodeRotationInfo)
{
if (nodeRotationInfo.Length == 1) return nodeRotationInfo[0].Rotation;
@@ -436,23 +423,10 @@ namespace Pal3.Renderer
CvdAnimationRotationKeyFrame fromKeyFrame = nodeRotationInfo[i];
var influence = (time - fromKeyFrame.Time) /
(toKeyFrame.Time - fromKeyFrame.Time);
Quaternion calculatedRotation = Quaternion.Lerp(
new Quaternion(fromKeyFrame.Rotation.X,
fromKeyFrame.Rotation.Y,
fromKeyFrame.Rotation.Z,
fromKeyFrame.Rotation.W),
new Quaternion(toKeyFrame.Rotation.X,
toKeyFrame.Rotation.Y,
toKeyFrame.Rotation.Z,
toKeyFrame.Rotation.W),
return Quaternion.Lerp(
fromKeyFrame.Rotation,
toKeyFrame.Rotation,
influence);
return new GameBoxQuaternion()
{
X = calculatedRotation.x,
Y = calculatedRotation.y,
Z = calculatedRotation.z,
W = calculatedRotation.w,
};
}
}
@@ -0,0 +1,53 @@
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
namespace Pal3.Renderer
{
using Core.GameBox;
using UnityEngine;
public interface IMaterialFactory
{
/// <summary>
/// Create a material for effect sprite without alpha channel.
/// </summary>
/// <returns>Material</returns>
public Material CreateOpaqueSpriteMaterial();
/// <summary>
/// Create a material for effect sprite without alpha channel.
/// </summary>
/// <param name="texture">Texture</param>
/// <returns>Material</returns>
public Material CreateOpaqueSpriteMaterial(Texture2D texture);
/// <summary>
/// Create standard materials.
/// </summary>
/// <param name="mainTexture">Main texture</param>
/// <param name="shadowTexture">Shadow texture</param>
/// <param name="tintColor">Tint color</param>
/// <param name="blendFlag">Blend flag</param>
/// <param name="transparentThreshold">Transparent threshold</param>
/// <returns>Materials</returns>
public Material[] CreateStandardMaterials(
Texture2D mainTexture,
Texture2D shadowTexture,
Color tintColor,
GameBoxBlendFlag blendFlag,
float transparentThreshold);
/// <summary>
/// Create material for water surface
/// </summary>
/// <param name="mainTexture">Main texture</param>
/// <param name="shadowTexture">Shadow texture</param>
/// <param name="alpha">Opacity</param>
/// <returns>Material</returns>
public Material CreateWaterMaterial(Texture2D mainTexture,
Texture2D shadowTexture,
float alpha);
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 2f037e2234e44a4097f71a02e05d18fb
timeCreated: 1665857882
@@ -0,0 +1,164 @@
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
namespace Pal3.Renderer
{
using Core.GameBox;
using UnityEngine;
using UnityEngine.Rendering;
public class LegacyMaterialFactory : MaterialFactoryBase, IMaterialFactory
{
// Pal3 legacy shaders
private const string OPAQUE_SHADER_PATH = "Pal3/Opaque";
private const string TRANSPARENT_SHADER_PATH = "Pal3/Transparent";
private const string TRANSPARENT_OPAQUE_PART_SHADER_PATH = "Pal3/TransparentOpaquePart";
private const string WATER_SHADER_PATH = "Pal3/Water";
// Standard material uniforms for Pal3 legacy shaders
private static readonly int MainTexturePropertyId = Shader.PropertyToID("_MainTex");
private static readonly int TintColorPropertyId = Shader.PropertyToID("_TintColor");
private static readonly int TransparentThresholdPropertyId = Shader.PropertyToID("_Threshold");
private static readonly int HasShadowTexturePropertyId = Shader.PropertyToID("_HasShadowTex");
private static readonly int ShadowTexturePropertyId = Shader.PropertyToID("_ShadowTex");
private static readonly int BlendSrcFactorPropertyId = Shader.PropertyToID("_BlendSrcFactor");
private static readonly int BlendDstFactorPropertyId = Shader.PropertyToID("_BlendDstFactor");
// Water material uniforms
private static readonly int WaterMainTexPropId = Shader.PropertyToID("_MainTex");
private static readonly int WaterShadowTexPropId = Shader.PropertyToID("_ShadowTex");
private static readonly int WaterAlphaPropId = Shader.PropertyToID("_Alpha");
private static readonly int WaterHasShadowTexPropId = Shader.PropertyToID("_HasShadowTex");
/// <inheritdoc/>
public Material CreateWaterMaterial(Texture2D mainTexture,
Texture2D shadowTexture,
float alpha)
{
var material = new Material(GetShader(WATER_SHADER_PATH));
material.SetTexture(WaterMainTexPropId,mainTexture);
material.SetFloat(WaterAlphaPropId, alpha);
if (shadowTexture != null)
{
material.SetFloat(WaterHasShadowTexPropId, 1.0f);
material.SetTexture(WaterShadowTexPropId, shadowTexture);
}
else
{
material.SetFloat(WaterHasShadowTexPropId, 0.5f);
}
return material;
}
/// <inheritdoc/>
public Material[] CreateStandardMaterials(
Texture2D mainTexture,
Texture2D shadowTexture,
Color tintColor,
GameBoxBlendFlag blendFlag,
float transparentThreshold)
{
Material[] materials = null;
if (blendFlag is GameBoxBlendFlag.AlphaBlend or GameBoxBlendFlag.InvertColorBlend)
{
materials = new Material[2];
materials[0] = CreateTransparentOpaquePartMaterial(mainTexture,
tintColor,
transparentThreshold,
shadowTexture);
materials[1] = CreateTransparentMaterial(mainTexture,
tintColor,
transparentThreshold,
shadowTexture);
BlendMode srcFactor;
BlendMode destFactor;
if (blendFlag == GameBoxBlendFlag.InvertColorBlend)
{
srcFactor = BlendMode.SrcAlpha;
destFactor = BlendMode.One;
}
else
{
srcFactor = BlendMode.SrcAlpha;
destFactor = BlendMode.OneMinusSrcAlpha;
}
materials[1].SetInt(BlendSrcFactorPropertyId, (int)srcFactor);
materials[1].SetInt(BlendDstFactorPropertyId, (int)destFactor);
}
else if (blendFlag == GameBoxBlendFlag.Opaque)
{
materials = new Material[1];
materials[0] = CreateOpaqueMaterial(mainTexture, tintColor, shadowTexture);
}
return materials;
}
private Material CreateTransparentMaterial(Texture2D mainTexture,
Color tintColor,
float transparentThreshold,
Texture2D shadowTexture)
{
var material = new Material(GetShader(TRANSPARENT_SHADER_PATH));
material.SetTexture(MainTexturePropertyId, mainTexture);
material.SetColor(TintColorPropertyId, tintColor);
material.SetFloat(TransparentThresholdPropertyId, transparentThreshold);
// shadow texture
material.SetFloat(HasShadowTexturePropertyId, 0.0f);
if (shadowTexture != null)
{
material.SetFloat(HasShadowTexturePropertyId, 1.0f);
material.SetTexture(ShadowTexturePropertyId, shadowTexture);
}
return material;
}
private Material CreateTransparentOpaquePartMaterial(Texture2D mainTexture,
Color tintColor,
float transparentThreshold,
Texture2D shadowTexture)
{
Material material = new Material(GetShader(TRANSPARENT_OPAQUE_PART_SHADER_PATH));
material.SetTexture(MainTexturePropertyId, mainTexture);
material.SetColor(TintColorPropertyId, tintColor);
material.SetFloat(TransparentThresholdPropertyId, transparentThreshold);
// shadow
material.SetFloat(HasShadowTexturePropertyId, 0.0f);
if (shadowTexture != null)
{
material.SetFloat(HasShadowTexturePropertyId, 1.0f);
material.SetTexture(ShadowTexturePropertyId, shadowTexture);
}
return material;
}
private Material CreateOpaqueMaterial(Texture2D mainTexture,
Color tintColor,
Texture2D shadowTexture)
{
Material material = new Material(GetShader(OPAQUE_SHADER_PATH));
material.SetTexture(MainTexturePropertyId, mainTexture);
material.SetColor(TintColorPropertyId, tintColor);
// shadow
material.SetFloat(HasShadowTexturePropertyId, 0.0f);
if (shadowTexture != null)
{
material.SetFloat(HasShadowTexturePropertyId, 1.0f);
material.SetTexture(ShadowTexturePropertyId, shadowTexture);
}
return material;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 886dbf38ae7fe41a9a3dad5f53f6aecb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,46 @@
// ---------------------------------------------------------------------------------------------
// Copyright (c) 2021-2022, Jiaqi Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ---------------------------------------------------------------------------------------------
namespace Pal3.Renderer
{
using System.Collections.Generic;
using UnityEngine;
public abstract class MaterialFactoryBase
{
private const string SPRITE_SHADER_PATH = "Pal3/Sprite";
// Sprite material uniforms
private static readonly int SpriteMainTexPropertyId = Shader.PropertyToID("_MainTex");
private readonly Dictionary<string, Shader> _shaders = new ();
public Material CreateOpaqueSpriteMaterial()
{
return new Material(GetShader(SPRITE_SHADER_PATH));
}
public Material CreateOpaqueSpriteMaterial(Texture2D texture)
{
var material = new Material(GetShader(SPRITE_SHADER_PATH));
material.SetTexture(SpriteMainTexPropertyId, texture);
return material;
}
internal Shader GetShader(string shaderName)
{
if (_shaders.ContainsKey(shaderName)) return _shaders[shaderName];
var shader = Shader.Find(shaderName);
if (shader != null)
{
_shaders[shaderName] = shader;
}
return shader;
}
}
}
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff. Show more